如何将绑定模型从视图传递回(非httppost)控制器方法

时间:2012-03-28 00:29:59

标签: asp.net-mvc asp.net-mvc-3

如何将(绑定的)模型从视图传递回不是[httppost]的控制器方法?

查看:

   @Html.EditorFor(model => model.Name)            
   @Html.DisplayFor(model => model.Model)   

   // Table displays more properties of model

   <input type="button" title="GetStuff" value="Get Stuff" onclick="location.href='@Url.Action("GetStuff")'" />

控制器方法:

  public ActionResult GetStuff(ViewModel Model /* Realize this is non-httppost but...how can I get the model back with this type of scenario */)
  {
    // Get the name from per the model of the main view if the user changed it
    string theName = Model.Name;

    Model2 m2 = new Model2(){name = theName};
    return ("someView", Model2);
  }

2 个答案:

答案 0 :(得分:2)

由于您在GET请求中传递数据的方式是通过查询字符串,因此您必须将所有数据放在查询字符串中。模型绑定可能起作用,至少对于简单模型,但您必须明确包含操作中的所有数据。例如:

@Url.Action("GetStuff", new { Name = Model.Name, Model = Model.Model })

但是如果这些数据中的任何一个很复杂,你就必须自己指定每个子属性......也许你应该发布? :)

答案 1 :(得分:2)

不是编写自己的查询字符串,只需将您的EditorFor内容包装在使用的Html.BeginForm()语句中,从按钮中删除Javascript,然后将按钮更改为提交类型。

    @using (Html.BeginForm("GetStuff", "Controller", FormMethod.Get)
    {
       @Html.EditorFor(model => model.Name)            
       @Html.DisplayFor(model => model.Model)   

   // Table displays more properties of model

       <input type="submit" title="GetStuff" value="Get Stuff"/>
    }

FormMethod.Get会将表单元素的查询字符串请求发送到Html.BeginForm定义中定义的action / controller。

相关问题