Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Contact contact)
{
using (LawContext DB = new LawContext())
{
if (ModelState.IsValid)
{
DB.Contact.Add(contact);
DB.SaveChanges();
return Json("OK");
}
return View();
}
}
View
@using (Html.BeginForm("Index", "Contact", FormMethod.Post))
{
@if (!ViewData.ModelState.IsValid)
{
@Html.ValidationSummary("", new { @class = "alert-danger" })
}
@Html.AntiForgeryToken()
@Html.TextBoxFor(m => m.Lastname, new { @class = "form-control margin-bottom10", @placeholder = "Name" })
@Html.TextBoxFor(m => m.Mail, new { @class = "form-control margin-bottom10", @placeholder = "Mail" })
@Html.TextBoxFor(m => m.Phone, new { @class = "form-control margin-bottom10", @placeholder = "Phone" })
@Html.TextAreaFor(m => m.Message, new { @class = "form-control margin-bottom10", @placeholder = "Message", @rows = "3" })
<input type="submit" value="Submit" class="btn btn-darkgray" id="btn_contact" />
}
JavaScript
$(document).ready(function () {
$("#btn_contact").click(function () {
$.ajax(
{
type: "POST",
url: "Contact/Index",
data: {
Lastname: $("#Lastname").val(),
Mail: $("#Mail").val(),
Phone: $("#Phone").val(),
Message: $("#Message").val()
},
dataType: "json",
async: true,
processData: false,
cache: false,
contentType: "application/json; charsetset=utf8",
success: function (data) {
alert('success');
},
failure: function (data) {
alert('failure');
},
error: function (data) {
alert('error');
}
});
});
});
I do not understand why this is happening Do not normally have to be alerted? How can I do this properly? I would like your help. I have studied many examples. I guess I lost hope I could do without asking.
I would like to work well.
indexaction onContactControllerwhich returns view that's why empty page with just ok. If you want to use ajax to call the same action try use a normal button give it idbtn_contact. The rest of the code looks fine. I haven't tested it, but it should work(pop an alert).$("#btn_contact").click(function (e) { e.preventDefault; $.ajax(....or addreturn false;as the last line of code in your method. As a side note there is no need to wrap@Html.ValidationSummary()in theifblockreturn View();makes no sense because you never do anything with the view you returndata: $('form').serialize(),and removecontentType: "application/json; charsetset=utf8",(the model in your POST method would not even be binding with your current code when you make the ajax POST). You can also removeasync: true,(that's the default)