1
好的,我已经遵循了几个关于如何使用Ajax.BeginForm()表示法提交表单的教程。一切似乎都很简单。但是,我注意到的(如下面的截图所显示的那样)是,尽管使用ajax,它仍然会重定向以显示结果而不是替换div的内容。为什么是这样?ASP.NET Ajax BeginForm重定向?
仅供参考,我一直在关注:Submit form using AJAX in Asp.Net mvc 4
CODE:
@Html.ValidationSummary(true)
@using (Ajax.BeginForm("Create", "Role", new AjaxOptions(){
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "RoleCreateResult",
HttpMethod = "POST"
}))
{
@Html.AntiForgeryToken()
<fieldset>
<div class="form-group">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" class="form-control" id="RoleName" name="RoleName" data-val-required="The Role name field is required." data-val="true" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="CreateRoleSubmit" class="btn btn-default" value="Save" />
</div>
</div>
</fieldset>
}
<div id="RoleCreateResult"></div>
控制器代码:
//
// POST: /Role/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(collection["RoleName"]))
{
return Json("Role " + collection["RoleName"] + " already exists.", JsonRequestBehavior.DenyGet);
}
else
{
var role = new IdentityRole();
role.Name = collection["RoleName"];
roleManager.Create(role);
return Json("Role " + collection["RoleName"] + " created successfully.",JsonRequestBehavior.DenyGet);
}
}
catch (Exception ex)
{
return Json("Error occured: " + ex.Message, JsonRequestBehavior.DenyGet);
}
}
渲染HTML:
个<form id="form0" method="post" data-ajax-update="#RoleCreateResult" data-ajax-mode="replace" data-ajax-method="POST" data-ajax="true" action="/Role/Create">
<input type="hidden" value="N2laLUmcoQ2yvbKwK40Sd6z1f56aZ2w_v0SQ-WfOcgCGnFaSAVNCkfjYatyU…E-NxRPPMueFOW4r-SVSpceGZX99iWsjpstd82URv4cRsNqbvf2UnJ0M1VWA2" name="__RequestVerificationToken"></input>
<fieldset>
<div class="form-group"></div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="CreateRoleSubmit" class="btn btn-default" type="submit" value="Save"></input>
</div>
</div>
</fieldset>
</form>
<div id="RoleCreateResult"></div>
屏幕:
我已经更新我的问题,包括我的控制器。它不返回一个局部视图,如果你不需要json,它会返回json – Kyle
@Kyle,你可以直接使用Content(“”)'结果。这听起来像你的JavaScript引用是不是引用或加载。你检查过了吗? – hutchonoid
是的,这似乎已经修复它,我的链接显然被破坏。虽然要谈谈你的另一点。返回上下文vs json与字符串等有什么区别? – Kyle