[英]Ajax.beginForms MVC Partial View
I am using an ajax.beginform to create a partial view within another view. 我正在使用ajax.beginform在另一个视图中创建局部视图。
I the user enters a correct sn everything works fine. 如果用户输入正确的sn,一切正常。 But if the user enters an invalid number, I want to redirect to the index view.
但是,如果用户输入的数字无效,我想重定向到索引视图。
Now the index page is submitted as a partial view in itself. 现在,索引页面本身已作为部分视图提交。
How can I avoid that. 我如何避免这种情况。
Here is a part of my view and 2 simplified actionresults. 这是我的观点的一部分,并提供2个简化的操作结果。
@using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST", UpdateTargetId = "form-content", InsertionMode =
InsertionMode.ReplaceWith }))
{
@Html.AntiForgeryToken()
<input type="text" id="sn" name="sn" class="inputsn"
placeholder="Enter your serial number here..." />
<input type="submit" value="Search" class="search btn btn-success btn-lg" />
}
</div>
</div>
<div id="form-content"></div>
my Controller 我的控制器
public ActionResult Index(bool? isValidMachine = null)
{
ViewBag.invalidSerialNumber = isValidMachine;
return View();
}
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if(string.IsNullOrEmpty(sn))
RedirectToAction("Index", new { isValidMachine = false });
QrCreateViewModel qrCreateVM;
using (var machineService = new MachineApiService())
{
var machine = machineService.GetMachineFromSerialNumber(sn);
if (machine == null)
return RedirectToAction("Index", new { isValidMachine = false });
else
qrCreateVM = new QrCreateViewModel(machine, GetBasePath());
}
if (qrCreateVM.IsValid())
{
qrCreateVM.Viewurl = qrCreateVM.QrCreateUrlOrDefaultNull();
return PartialView(qrCreateVM);
}
else
return RedirectToAction("Index", new { isValidMachine = false });
}
Ajax calls do not redirect (the purpose of making them is to stay on the same page). Ajax调用不会重定向(进行调用的目的是保持在同一页面上)。
In your controller method, replace the instances of return RedirectToAction(...)
to return a HttpStatusCodeResult
indicating an error, which you can then handle in the OnFailure
option to redirect to the Index()
method. 在你的控制器的方法,更换的情况下,
return RedirectToAction(...)
返回一个HttpStatusCodeResult
指示错误,然后你就可以在处理OnFailure
选项重定向到Index()
方法。
For example 例如
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if (string.IsNullOrEmpty(sn))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
....
Then in the Ajax.BeginForm()
然后在
Ajax.BeginForm()
@using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST",
UpdateTargetId = "form-content",
InsertionMode = InsertionMode.ReplaceWith,
OnFailure = "redirect"
}))
{
....
and add the following script to redirect 并添加以下脚本进行重定向
function redirect(ajaxContext) {
location.href = '@Url.Action("Index")';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.