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
You should add
dataType
&contentType
like below.An alternative way to handle the values for your form:
And your
Controller
will look like: