MVC3中的多种形式

本文关键字:多种形式 MVC3 | 更新日期: 2023-09-27 18:29:39

我有一个带有表单的网页,看起来有点像:

@using (Html.BeginForm("MyAction", "Controller", FormMethod.Post))
{
    // html input fields here
    // ...
    // [SUBMIT]
}

当用户按下提交按钮时,将调用以下功能:

public ActionResult MyAction ( string id )
{
    // default action
}
[HttpPost]
public ActionResult MyAction ( MyModel model )
{
    // called when a form is submitted
}

现在我的问题是,我必须添加另一个表格。但我如何判断提交的是哪一个表格?因为两者现在都将在第二个(HttpPost)方法中结束。。。

将两种形式的动作分开的好方法是什么?请注意,当提交表格时,我必须保持在同一页上。我无法将自己重定向到另一个页面/控制器。

MVC3中的多种形式

如果我正确理解你的问题,你会有一个包含两个表单的页面。作为第一种方法,我将把每个表单发布到同一控制器的不同动作。

第一个

@using (Html.BeginForm("MyAction", "Controller", FormMethod.Post))

第二个

@using (Html.BeginForm("MyAction2", "Controller", FormMethod.Post))

然后,对您的两个操作进行一点重构,以遵循DRY原则。

如果你需要两个表单发布到同一个操作,那么我会放一个隐藏的输入,让我知道哪个表单被调用了。

如果您在一个页面/视图上有多个表单,并且希望发布到不同的操作,请将name html属性添加到beginform方法:

@using (Html.BeginForm("action1", "contollerName", new { @name = "form1" }))
{
    ...add view code
}
@using (Html.BeginForm("action2", "contollerName", new { @name = "form2" }))
{
    ...add view code
}

为每个表单指定不同的名称将使MVC能够轻松地确定要发布到哪个操作,而不是依赖于不同的表单集合值来确定这一点。

如果您想在不重定向的情况下查看数据,我建议您使用JQueryAjax。您可以使用以下内容作为样本

 $(document).ready(function(){
    $('#IdOfButton').click(function(){ 
      $.ajax({
        url: '/Controller/MyAction',
        type: 'POST',
        data: {
           PropertyInModel : ValueFromView
           //for values you need to pass from view to controller
        },
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data.success);
        },
        error: function () {
            alert("error");
        }
    });
    });
});

你的动作看起来像这个

 [HttpPost]
    public ActionResult MyAction ( MyModel model )
    {
        // called when a form is submitted
        return Json(new { success = true });
    }