所有
我正在尝试实现表单的AJAX帖子。(ASP.NET MVC的新功能,来自Rails背景)
当我提交表单并观看FireBug控制台以及页面时,表单不会执行AJAX帖子。调用AJAX处理程序(Contact / Process)并将表单重定向到那里,显示响应消息的Contact / Process,而不是更新表单上的指定div
我必须在某个地方实现错误,很可能是在处理AJAX POST的控制器中。还不确定还有什么。
由于
表单(/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>
控制器操作(/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";
}
答案 0 :(得分:2)
您需要这两个库:
<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>
<强>更新强>
您的流程操作需要返回ActionResult
并使用Content
而不是字符串。
将其更改为:
[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");
}
答案 1 :(得分:1)
您需要将jquery脚本添加到页面
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>