![](/img/trans.png)
[英]Can I send a message instead of a view back as an ActionResult with ASP.NET MVC4
[英]MVC: return View() is going back to http ActionResult instead of rendering View
我有一個表格:
@using (Html.BeginForm()){
<dl class="dl-horizontal">
<dt>@Html.LabelFor(m => m.VerifiedBy)<dt>
<dd>@Html.TextBoxFor(m => m.VerifiedBy)</dd>
</dl>
<input type="submit" value="Verify" onclick="checkValueVerify();" />
}
如果用戶單擊“驗證”按鈕而未輸入“驗證”的值,則JavaScript函數checkValueVerify將發送警報,然后指向HttpPost驗證ActionResult。
JavaScript的:
function checkValueVerify() {
if (document.getElementById("verifiedBy").value== "") {
alert('Must enter name of verifier');
}
$.ajax({
url: '/GAC/Verify',
type: 'POST',
data: {'by': verifBy}
});
}
控制器:
[HttpPost]
public ActionResult Verify(GACVerifyViewModel viewModel,string by)
{
if(by==null)
{
//code
return View();
}
當我單步執行代碼時,它從return View
到Verify.cshtml到Layout.cshtml,這是我所期望的。 但是,在Layout.cshtml的末尾,它返回到[HttpPost] Verify
,此時我的參數為null。
所以流程是HttpPost驗證 - > Verify.cshtml - > HttpPost驗證(控制器 - >視圖 - >控制器。為什么它會回到我的HttpPost ActionResult驗證控制器而不是僅渲染視圖?
這是因為您的表單發送回發請求並提交表單,您應該防止提交按鈕的默認行為。 只需添加event.preventDefault
或在javascript函數結束時return false
我認為這里發生的是你的表格被發布兩次。
一旦通過Ajax調用,然后再通過標准提交輸入。
一個簡單的修復應該是添加return false,例如:
<input type="submit" value="Verify" onclick="checkValueVerify(); return false;" />
返回false是停止發布表單的提交輸入,以便只發布Ajax函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.