简体   繁体   中英

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:

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. However, at the end of Layout.cshtml, it goes back to [HttpPost] Verify and my parameter is null at this point.

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?

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

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.

a simple fix should be to add return false eg:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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