简体   繁体   English

MVC:返回View()返回到http ActionResult,而不是渲染View

[英]MVC: return View() is going back to http ActionResult instead of rendering View

I have a form: 我有一个表格:

@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();" />
}

If the user clicks the Verify button without entering a value for Verified by, the JavaScript function checkValueVerify will send an alert and then direct to the HttpPost Verify ActionResult. 如果用户单击“验证”按钮而未输入“验证”的值,则JavaScript函数checkValueVerify将发送警报,然后指向HttpPost验证ActionResult。

JavaScript: JavaScript的:

function checkValueVerify() {
    if (document.getElementById("verifiedBy").value== "") {
         alert('Must enter name of verifier');
    } 
    $.ajax({
        url: '/GAC/Verify',
        type: 'POST',
        data: {'by': verifBy}
    });
}

Controller: 控制器:

[HttpPost]
public ActionResult Verify(GACVerifyViewModel viewModel,string by)
{
    if(by==null)
        {
            //code                
            return View();
        }

When I step through the code, it goes from return View to Verify.cshtml to Layout.cshtml which is what I expect. 当我单步执行代码时,它从return View到Verify.cshtml到Layout.cshtml,这是我所期望的。 However, at the end of Layout.cshtml, it goes back to [HttpPost] Verify and my parameter is null at this point. 但是,在Layout.cshtml的末尾,它返回到[HttpPost] Verify ,此时我的参数为null。

So the flow is HttpPost Verify -> Verify.cshtml -> HttpPost Verify (controller -> view -> controller. Why is it going back to my HttpPost ActionResult Verify in the controller instead of just rendering the view? 所以流程是HttpPost验证 - > Verify.cshtml - > HttpPost验证(控制器 - >视图 - >控制器。为什么它会回到我的HttpPost ActionResult验证控制器而不是仅渲染视图?

it's because your form sends a post back request and submits the form, you should prevent default behavior of submit button. 这是因为您的表单发送回发请求并提交表单,您应该防止提交按钮的默认行为。 simply add event.preventDefault or return false at the end of javascript function 只需添加event.preventDefault或在javascript函数结束时return false

What I believe is happening here is that your form is being posted twice. 我认为这里发生的是你的表格被发布两次。

Once via the Ajax call and then again via the standard submit input. 一旦通过Ajax调用,然后再通过标准提交输入。

a simple fix should be to add return false eg: 一个简单的修复应该是添加return false,例如:

<input type="submit" value="Verify" onclick="checkValueVerify(); return false;" />

The return false is to stop the submit input posting the form so that only the Ajax function will post. 返回false是停止发布表单的提交输入,以便只发布Ajax函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM