Ajax.beginForms MVC局部视图

Ajax.beginForms MVC局部视图

问题描述:

我正在使用ajax.beginform在另一个视图中创建局部视图。Ajax.beginForms MVC局部视图

我用户输入正确的sn一切正常。 但是,如果用户输入一个无效的号码,我想重定向到索引视图。

现在,索引页面本身作为局部视图提交。

我该如何避免这种情况。

这是我的观点和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> 

我控制器

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 }); 
    } 
+1

Ajax调用不能重定向 - 他们的整点是留在同一页上。一种选择是在不返回部分视图的情况下抛出一个Http Error,然后使用'OnFailure' ajax选项来调用一个脚本,重定向到你的'Index()'方法(尽管这更容易你摆脱了过时的'Ajax.BeginForm()'并使用'$ .ajax()',这给你更多的灵活性 –

+0

谢谢你的回答我试图找出你的第一个建议,它的工作原理,我知道beter选项是与jquery Ajax一起工作的,但是这个决定并不在我的手中 我不想接受你的评论作为一个很好的答案,但那是行不通的 –

+0

它迟到了,但我会添加在早上的详细答案 –

Ajax调用不重定向(使他们的目的是要留在同一页上)。

在你的控制器的方法,更换的return RedirectToAction(...)的情况下返回一个HttpStatusCodeResult指示错误,然后你就可以在OnFailure选项处理重定向到Index()方法。

例如

[HttpPost] 
public ActionResult MachineInfo(string sn) 
{ 

    if (string.IsNullOrEmpty(sn)) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request"); 
    } 
    .... 

然后在Ajax.BeginForm()

@using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() { 
    HttpMethod = "POST", 
    UpdateTargetId = "form-content", 
    InsertionMode = InsertionMode.ReplaceWith, 
    OnFailure = "redirect" 
})) 
{ 
    .... 

,并添加下面的脚本重定向

function redirect(ajaxContext) { 
    location.href = '@Url.Action("Index")'; 
} 
+0

该代码充满了Ajax。*助手。 我知道你有更多的灵活性,如果你使用JQuery的AJAX。 但我想如果这影响到性能? –

+0

只有你必须在视图中加载'jquery.unobtrusive-ajax.js'文件的事实,但它很小。作为一个方面说明,不再支持'Ajax'助手 –

+0

如果有暴风雪和我在同一栋建筑中被*2天,我会对它们进行重构:) –