开发者

ASP.NET MVC3 Html.Action containing a form

开发者 https://www.devze.com 2023-03-03 16:07 出处:网络
I have a pod on my page that conta开发者_运维问答ins a form. I have used this pod in a similar way to the following:

I have a pod on my page that conta开发者_运维问答ins a form.

I have used this pod in a similar way to the following:

@Html.Action("Pod","Home")

There is some business rule checking in the Pod's HttpPost action which handles the form post. If this business rule fails, I add an error to the model state.

The problem is, that when the business rule fails to validate. I return a View from the pod action, which shows just the pod on a blank page.

How can I correctly reuse a form like this and still have server side validation of this business rule (requires a db hit to validate)?


One possibility is to AJAXify the form in the Pod partial:

<div id="pod">
    @Html.Action("Pod","Home")
</div>

and inside Pod.cshtml:

@using (Html.BeginForm("Pod", "Home", FormMethod.Post, new { id = "podForm" }))
{
    ...
}

finally AJAXify it:

$(function() {
    $('#podForm').submit(function() {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
                $('#pod').html(result);
            }
        });
    });
});

The last thing to make sure is that the POST action returns the Pod.cshtml as a partial view. Two possibilities:

[HttpPost]
public ActionResult Pod(PodViewModel model)
{
    if (!ModelState.IsValid)
    {
        return PartialView(model);
    }
    ...
}

or in the Pod.cshtml partial:

@{
    Layout = null;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消