skip to Main Content

I am trying to save data in database from a form with $.ajax. The problem is that when I submit the form the username is saved as null. The email and password are saved correctly.

function SaveForm() {
  var name = $("#User").val();
  var pwd = $("#Password").val();
  var email = $("#Email").val();
  if (name == "" || pwd == "" || email == "") {
      $("#message1").hide();
      $("#message2").show();
      return false;
  }
  var data =  $("#Registration").serialize();
  $.ajax({
      type: "post",
      data: data,
      url: "/Registration/SaveData",
      success: function (result) {
          $("#message1").show();
          $("#message2").hide();
          $("#Registration")[0].reset();
      }            
  });
}
<div class="modal-body">
  <form id="Registration">
      <div class="form-group">
          <div class="input-group">
              <span class="input-group-addon"><i class="fa fa-user"></i></span>
              <input class="form-control" type="text" name="User" id="User" placeholder="UserName" />
          </div>
      </div>
      <div class="form-group">
          <div class="input-group">
              <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
              <input class="form-control" type="email" name="Email" id="Email" placeholder="Email" />
          </div>
      </div>
      <div class="form-group">
          <div class="input-group">
              <span class="input-group-addon"><i class="fa fa-lock"></i></span>
              <input class="form-control" type="password" name="Password" id="Password" placeholder="Password" />
          </div>
      </div>
  </form>
  <div class="form-group">
      <button class="btn btn-info form-control" type="submit" onclick="SaveForm()"><i class="fa fa-paper-plane"></i>Submit</button>
  </div>
</div>
public JsonResult SaveData(SiteUser model) {
    model.IsValid = false;
    db.SiteUsers.Add(model);
    db.SaveChanges();
    BuildEmailTemplate(model.ID);
    return Json("Registration Successfull", JsonRequestBehavior.AllowGet); 
}

2

Answers


  1. You should add dataType & contentType like below.

    $.ajax({
      dataType: 'json',   
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
      type: "post",
      data: $("#Registration").serialize(),
      url: "/Registration/SaveData",
      success: function (result) {
          $("#message1").show();
          $("#message2").hide();
          $("#Registration")[0].reset();
      }            
    });
    
    Login or Signup to reply.
  2. An alternative way to handle the values for your form:

    function SaveForm() {
      var name = $("#User").val();
      var pwd = $("#Password").val();
      var email = $("#Email").val();
    
      var json = {
              name:name,
              pwd:pwd,
              email:email
             };
    
      if (name == "" || pwd == "" || email == "") {
          $("#message1").hide();
          $("#message2").show();
          return false;
      }
    
      $.ajax({
          type: "post",
          dataType: "json",
          data: {"json": JSON.stringify(json)},,
          url: "@Url.Action("SaveData","Registration")",
          success: function (result) {
              $("#message1").show();
              $("#message2").hide();
              $("#Registration")[0].reset();
          }            
      });
    }
    

    And your Controller will look like:

    using System.Web.Script.Serialization;
    
    [HttpPost]
    public JsonResult SaveData(string json) 
    {
    
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));
    
        //Get your variables here from AJAX call
        var name= jsondata["name"];
        var pwd= jsondata["pwd"];
        var email= jsondata["email"];
    
        //Set your model here:
        SiteUser model=new SiteUser();
        model.name=name;
        model.pwd=pwd;
        model.email=email;
    
        //Perform db actions
        db.SiteUsers.Add(model);
        db.SaveChanges();
        BuildEmailTemplate(model.ID);
        return Json("Registration Successfull", JsonRequestBehavior.AllowGet); 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search