2012-04-02 124 views
2

我有一个形式,它看起来有点像这样的网页:多种形式

@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)方法中结束...

什么是分离两种表单操作的好方法?请注意,提交表格时,我必须保持在同一页面上。我无法将自己重定向到其他页面/控制器。

回答

5

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

第一

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

第二

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

,然后,在你的两个动作一点点重构跟随DRY principle

如果您需要两种表单来发布相同的动作,那么我会提供一个隐藏的输入让我知道被调用的人。

+0

我也想过,但是这两个操作都会有相同的代码,比如从数据库中获取数据。你在谈论DRY,这是否意味着在我的控制器中创建一个私有方法是完全可以的,这两个Actions都可以使用? – Vivendi 2012-04-02 09:41:14

+1

是的,为什么不呢?您可以在许多地方调用函数来重构代码。你也可以考虑创建一个扩展方法,但我不知道你在代码中做了什么。 – Iridio 2012-04-02 09:44:09

1

如果你想查看没有重定向的数据,我建议你使用JQuery Ajax。您可以使用下面的示例

$(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 }); 
    } 
+0

当您需要返回模型上的错误时,您会做什么?例如,如果(ModelState.IsValid)的计算结果为false,并且只想将模型返回到视图并使ValidationSummary显示模型错误。 – 2012-04-02 12:36:39

3

如果你有一个网页/视图多种形式,想张贴到不同的操作添加姓名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容易确定发布一个行动,而不是依靠不同的形式收集值来解决这个问题。