【问题标题】:ASP.NET MVC3 Html.Action containing a form包含表单的 ASP.NET MVC3 Html.Action
【发布时间】:2011-05-06 12:53:17
【问题描述】:

我的页面上有一个包含表单的 pod。

我使用这个 pod 的方式与以下类似:

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

在处理表单发布的 Pod 的 HttpPost 操作中有一些业务规则检查。如果此业务规则失败,我会在模型状态中添加一个错误。

问题是,当业务规则无法验证时。我从 pod 操作返回一个 View,它仅在空白页面上显示 pod。

我怎样才能正确地重用这样的表单并且仍然对该业务规则进行服务器端验证(需要 db hit 来验证)?

【问题讨论】:

  • 我们已经到 MVC3 了吗?我到底去哪儿了?哦。等等,正在处理旧版 ASP 经典网站。

标签: forms asp.net-mvc-3 child-actions


【解决方案1】:

一种可能性是在Pod partial 中对表单进行 AJAX 化:

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

Pod.cshtml内部:

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

终于 AJAXify 了:

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

最后要确保的是 POST 操作将 Pod.cshtml 作为局部视图返回。两种可能:

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

或在Pod.cshtml部分:

@{
    Layout = null;
}

【讨论】:

  • 很好,但你需要添加“return false;” ajax 调用后添加到您的 javascript 代码中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多