2012-03-28 85 views
0

如何從視圖傳遞(綁定)模型到不是[httppost]的控制器方法?如何將綁定模型從視圖傳遞迴(非-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

不用編寫自己的查詢字符串,只需將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定義中定義的動作/控制器的查詢字符串請求。

+0

你能告訴我控制器的標誌是什麼樣子嗎? – JaJ 2012-03-30 20:04:07

+0

就像你在你的問題中應該可以正常工作。 – Tommy 2012-03-30 20:55:17

2

既然你在GET請求傳遞數據的方式是通過查詢字符串,你必須提上查詢所有數據串。模型綁定可能起作用,至少對於簡單模型來說,但您必須明確地包含操作中的所有數據。例如:

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

但是,如果任何數據是複雜的,你必須指定每個子屬性自己......也許你應該剛剛張貼? :)

相關問題