All,
I am trying to implement an AJAX post of a form.(New to ASP.NET MVC,coming from a Rails background)
When I submit the form and watch the FireBug console as well as the page, the form is not doing an AJAX post. The AJAX handler gets invoked (Contact/Process) and the form redirects there, to Contact/Process showing just the response message, instead of updating the designated div on the form
I must be implementing something wrong some place, most likely in the controller that handles the AJAX POST. Not sure what else.
Thanks
The Form (/Views/Contact/Create.cshtml)
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div id="content">
<div id="Status"></div>
@using (Ajax.BeginForm("Process","Contact", new AjaxOptions{ HttpMethod = "POST", UpdateTargetId = "Status"}))
{
@Html.ValidationSummary(true)
<p><span class="required">* All fields are required.</span></p>
<!-- First Name -->
<div>
@Html.LabelFor(model => model.Contact.FirstName) <span class="required">*</span>
</div>
@Html.EditorFor(model => model.Contact.FirstName)
@Html.ValidationMessageFor(model =>model.Contact.FirstName)
<div>
<input type="submit" name="submit" value="Submit" class="btn"/>
</div>
}
</div>
The Controller Action (/Controllers/ContactController.cs)
[HttpPost]
public string Process(ContactViewModel c)
{
if (ModelState.IsValid)
{
c.Contact.DateCreated = DateTime.Now;
db.Contacts.Add(c.Contact);
db.SaveChanges();
return "Success!";
}
return "Failure";
}
You need these two libraries:
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Update
Your Process action needs to return an ActionResult
and use Content
rather than a string.
Change it to this:
[HttpPost]
public ActionResult Process(ContactViewModel c)
{
if (ModelState.IsValid)
{
c.Contact.DateCreated = DateTime.Now;
db.Contacts.Add(c.Contact);
db.SaveChanges();
return Content("Success!");
}
return Content("Failure");
}
您需要将jquery脚本添加到页面
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.