return type is getting null while having data passed in it

this is my form I am using mvc in VS2013 where I am little confused about whats happening here, it is returning me empty fields while I am passing required data, although it is ok when fields are empty but when it has data in it it should be fired a successfully sent it but it is not working
guys please help me to get my this code working

View

@using (Html.BeginForm("RegUser", "User", FormMethod.Post, new { @id = "myForm" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div class="form-horizontal custom_frmHorizontal">
        <fieldset>

            <!-- Form Name -->
            <!-- Text input-->
            <div class="form-group">

                <div class="col-md-12">
                    @*@Html.HiddenFor(model => model.Subscription)*@
                    @Html.TextBoxFor(model => model.CompanyName, new { @class = "form-control input-md", @autocomplete = "off", @placeholder = "Company Name", @id = "txtName" })
                    @Html.ValidationMessageFor(model => model.CompanyName, null, new { @class = "text-danger" })
                    <span id="ern" class="field-validation-error text-danger" data-valmsg-for="CompanyName" data-valmsg-replace="true" style="display:none;"></span>
                </div>
            </div>
            <div class="form-group">
                @*<label class="col-md-4 control-label" for="textinput">Email Address :</label>*@
                <div class="col-md-12">
                    @*<input id="textinput" name="textinput" type="text" placeholder="Email Address" class="form-control input-md">*@

                    @Html.TextBoxFor(model => model.Email, new { @class = "form-control input-md", @style = "background-color:transparent !important;", @autocomplete = "off", @placeholder = "Email Address", @id = "txtemail" })
                    @Html.ValidationMessageFor(model => model.Email, null, new { @class = "text-danger" })
                    <span id="ere" class=" field-validation-error text-danger" data-valmsg-for="Email" data-valmsg-replace="true" style="display:none;"></span>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-12">

                    @Html.TextBoxFor(model => model.Mobile, new { @class = "form-control input-md", @autocomplete = "off", @placeholder = "Phone Number", @id = "txtMobile" })
                    @Html.ValidationMessageFor(model => model.Mobile, null, new { @class = "text-danger" })
                    <span id="ermob" class=" field-validation-error text-danger" style="display:none;"></span>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-12">

                    @Html.TextBoxFor(model => model.CRN, new { @class = "form-control input-md", @autocomplete = "off", @placeholder = "Company CRN", @id = "txtCrn" })
                    @Html.ValidationMessageFor(model => model.CRN, null, new { @class = "text-danger" })
                    <span id="ercrn" class=" field-validation-error text-danger" style="display:none;"></span>

                </div>
            </div>
            <div class="form-group">
                <div class="col-md-12">

                    @Html.TextBoxFor(model => model.EmpStrength, new { @class = "form-control", @autocomplete = "off", @placeholder = "Employees Strength", @id = "txtEmpStr" })
                    @Html.ValidationMessageFor(model => model.EmpStrength, null, new { @class = "text-danger" })
                    <span id="eremp" class="field-validation-error text-danger" style="display:none;"></span>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-12">

                    @Html.TextBoxFor(model => model.Address, new { @class = "form-control input-md", @autocomplete = "off", @placeholder = "Company Address", @id = "txtCadrs" })
                    @Html.ValidationMessageFor(model => model.Address, null, new { @class = "text-danger" })
                    <span id="eradrs" class="errmsg field-validation-error text-danger" style="display:none;"></span>
                </div>
            </div>
            <div class="form-group btn_wrap">
                <div class="col-md-12">
                        <button id="formSubmit" value="Submit" type="submit" class="btnCutom1 btn btn-primary">Send Request<i class="far fa-paper-plane pl-3"></i></button>
                </div>
            </div>
        </fieldset>
    </div>
}

Jquery

$('#myForm').on('submit', function(event) {
  var frmData = $("myForm");
  event.preventDefault()

  var name = document.getElementById('txtName').value;
  var email = document.getElementById('txtemail').value;
  var mobile = document.getElementById('txtMobile').value;
  var crn = document.getElementById('txtCrn').value;
  var emp = document.getElementById('txtEmpStr').value;
  var adrs = document.getElementById('txtCadrs').value;

  if (name.length == 0) {
    //alert("Please insert Company Name");
    $("#ern").text("Company name must required").fadeIn();
  }
  if (email.length == 0) {
    $("#ere").text("Please insert email address").fadeIn();
  }
  if (mobile.length == 0) {
    //alert("Please insert Mobile Number");
    $("#ermob").text("Please insert Mobile Number").fadeIn();
  }
  if (crn.length == 0) {
    //alert("Please insert CRN");
    $("#ercrn").text("Please insert CRN").fadeIn();
  }
  if (emp.length == 0) {
    //alert("Please insert Employees");
    $("#eremp").text("Please insert Employees Strength").fadeIn();
  }
  if (adrs.length == 0) {
    //alert("Please insert Address");
    $("#eradrs").text("Please insert Company Address").fadeIn();
  } else {

    //var frmData = $("myForm");
    //e.preventDefault();
    $.ajax({
      type: "Post",
      ContentType: "application/json; charset=utf-8",
      data: "{frmData:" + JSON.stringify(frmData) + "}",
      // url: "pricing/Index",                   
      success: function(data) {
        alert("sent successfully:" + data);
        location.window.href = "RegUser/User";

      },
      error: function(result) {
        //$form = $(this);
        alert("something went wrong");
      }

    });
  }
});

Controller

public class UserController : Controller
{
    //
    // GET: /User/
    [HttpGet]
    public ActionResult RegUser(int id=0)
    {
        UserDtl userModel = new UserDtl();
        return View(userModel);
    }

    [HttpPost]
    public ActionResult RegUser(UserDtl userModel, string CompanyName, string Email, string CRN, string EmpStrength, string Mobile, string Address)
    {
        try
        {
            using (DbModels dbModel = new DbModels())
            {
                dbModel.UserDtls.Add(userModel);
                dbModel.SaveChanges();
            }
            if (ModelState.IsValid)
            {
                var senderemail = new MailAddress("shakil.7878@gmail.com", "deem-admin");
                var receiveremail = new MailAddress(Email, "New Request");
                var password = "inDia123#";
                var sub = CompanyName;
                string bodyText = string.Format("<table border='0' cellpadding='0' cellspacing='0' style='width:600px; background:#efefef;'> <tr><td colspan='2'><center><img src='https://drcoder1tcircle.000webhostapp.com/mh.jpg' /></center></td></tr><tr><td colspan='2'><center><img src='https://drcoder1tcircle.000webhostapp.com/ms.jpg' /></center></td></tr> <tr><td style='height:40px;'></td> <td style='height:40px;'></td></tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'><b>New Request</b></td><td> </td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Company Name: </td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{0}</td> </tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Email Address: </td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{1}</td> </tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Company Registration No.</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{2}</td> </tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Employees Strength</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{3}</td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Mobile No.</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{4}</td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Company Address</td>  <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{5}</td> </tr>  <tr><td style='height:40px;'></td> <td style='height:40px;'></td></tr>  <tr><td style='background:#303030; height:30px;' colspan='2'><center><a style='color:#ffffff; text-align:center; font-family:Arial; font-size:12px;' href='#' target='_blank'>www.deem.sa</a></center></td></tr> </table>", CompanyName, Email, CRN, EmpStrength, Mobile, Address);
                var body = bodyText;                    
                var smtp = new SmtpClient
                    {Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(senderemail.Address, password)};
                var mess = new MailMessage(senderemail, receiveremail)
                    {Subject = sub,
                    Body = body,
                    IsBodyHtml = true};                    
                smtp.Send(mess);
                ModelState.Clear();
                ViewBag.SuccessMessage = "Request sent Successful. We will send you Registration Details on your email address.";
                return View();
            }
            //ModelState.Clear();
            //ViewBag.SuccessMessage = "Request sent Successful. We will send you Registration Details on your email address.";            
        }
        catch (Exception ex)
        {
        }
        return View("RegUser", new UserDtl());
    }
}

2 answers

  • answered 2018-07-12 07:46 Pancake

    You can't specify the DOM id for your input elements like this (@id = "txtName"). The id is automatically generated by the framework. If you view the source in your browser, you will see these elements have been rendered with 2 ids. This is invalid HTML, causing your breakage.

    There are accepted answers to other questions here on SO basically saying you can capitalize @id to fix this (i.e. @Id), but the users providing these answers don't understand how the attributes on these elements are generated, and are simply observing a side effect of a hack that is not actually guaranteed to work in any scenario, though it may happen to work in a few browsers under certain conditions right now.

    Instead, remove any use of "@id=", and use the @Html.IdFor() helper to determine the assigned ID. For example:

    <script>
    var myId = "@Html.IdFor(m => m.CompanyName)";
    </script>
    

    You would then use this Javascript variable (e.g. myId) in place of the ID you invented ("txtName") in the rest of your code .. for example, you'd change this:

    var name = document.getElementById('txtName').value;
    

    To this:

    var name = document.getElementById(myId).value;
    

    And since you're using jQuery, you may alternatively express this as follows:

    var name = $("#" + myId).val();
    

    Then the generated HTML will be valid and your form will post as expected.

  • answered 2018-07-12 10:22 Designwala Solution

    $('#myForm').on('submit', function (event) {
        var frmData = $("myForm");
      //  event.preventDefault()
    
        var myCn = "@Html.IdFor(m => m.CompanyName)";
        var myEm = "@Html.IdFor(m => m.Email)";
        var myMo = "@Html.IdFor(m => m.Mobile)";
        var myCr = "@Html.IdFor(m => m.CRN)";
        var myEp = "@Html.IdFor(m => m.EmpStrength)";
        var myAd = "@Html.IdFor(m => m.Address)";
    
        var name = document.getElementById(myCn).value;
        var email = document.getElementById(myEm).value;
        var mobile = document.getElementById(myMo).value;
        var crn = document.getElementById(myCr).value;
        var emp = document.getElementById(myEp).value;
        var adrs = document.getElementById(myAd).value;
    
        //var name = $("#" + myCn).val();
        //var email = $("#" + myEm).val();
        //var mobile = $("#" + myMo).val();
        //var crn = $("#" + myCr).val();
        //var emp = $("#" + myEp).val();
        //var adrs = $("#" + myAd).val();
    
    
        if (name.length == 0) {
            //alert("Please insert Company Name");
            $("#ern").text("Company name must required").fadeIn();
        } if (email.length == 0) {
            $("#ere").text("Please insert email address").fadeIn();
        } if (mobile.length == 0) {
            //alert("Please insert Mobile Number");
            $("#ermob").text("Please insert Mobile Number").fadeIn();
        }
        if (crn.length == 0) {
            //alert("Please insert CRN");
            $("#ercrn").text("Please insert CRN").fadeIn();
        }
        if (emp.length == 0) {
            //alert("Please insert Employees");
            $("#eremp").text("Please insert Employees Strength").fadeIn();
        }
        if (adrs.length == 0) {
            //alert("Please insert Address");
            $("#eradrs").text("Please insert Company Address").fadeIn();
        }
        else {
    
            //var frmData = $("myForm");
            //e.preventDefault();
            $.ajax({
                type: "Post",
                ContentType: "application/json; charset=utf-8",
                data: "{frmData:" + JSON.stringify(frmData) + "}",
                // url: "pricing/Index",
                success: function (data) {
                    alert("sent successfully:" + data);
                    location.window.href = "RegUser/User";
    
                },
                error: function (result) {
                    //$form = $(this);
                    alert("something went wrong");
                }
    
            });
        }
    
    });