2009-11-25 94 views
1

我正在處理一些MVC,我需要將表單動態地路由到某個操作和參數組合。到目前爲止,我有這樣的:ASP.NET MVC - 表單的動態操作和參數

PageViewModel 
{ 
    public string Action {get;set;} 
    public string Parameter {get;set;} 
    /*... other properties for the form */ 
} 

PageController 
{ 
    public ViewResult MyAction(string myParamterName) { 
    return View("CommonView", 
     new PageViewModel{Action="MyAction", Parameter="myParameterName")); 
    } 
    public ViewResult YourAction(string yourParamterName) { 
    return View("CommonView", 
     new PageViewModel{Action="YourAction", Parameter="yourParameterName")); 
    } 
    /* ... and about 15 more of these */ 
} 

CommonView.aspx:

<%-- ... --%> 
<% using (Html.BeginForm(Model.Action,"PageController",FormMethod.Get)) {%> 
    <%=Html.TextBox(Model.Parameter)%> 
    <input id="submit" type="submit" value="Submit" /> 
<%}%> 
<%-- ... --%> 

這工作,但它得到了很多串漂浮的告訴它到哪裏去。

我想要的是一種在視圖內定義窗體參數的類型安全方法,但我在如何實現這一點方面有點失落。也許,一些看起來像這樣 -

<% using (Html.BeginForm<PageController>(Model.??ExpressionToGetAction??)) {%> 
    <%=Html.TextBox(Model.??ExpressionToGetParameter??)%> 
    <input id="submit" type="submit" value="Submit" /> 
<%}%> 

或者,有沒有辦法從路由數據獲得用於生成這種觀點的動作和參數,也許?

還是應該有一個自定義的路由方案,可以處理所有這些自動?

所以,我真正想要的是最優雅和類型安全的方式來實現這一點。謝謝!

編輯

由於喬希指出,表單將提交回動作。這個有點修剪代碼:

PageViewModel 
{ 
    public string ParameterName {get;set;} 
    /*... other properties for the form */ 
} 

PageController 
{ 
    public ViewResult MyAction(string myParamterName) { 
    return View("CommonView", 
     new PageViewModel{ParameterName ="myParameterName")); 
    } 
    public ViewResult YourAction(string yourParamterName) { 
    return View("CommonView", 
     new PageViewModel{ParameterName ="yourParameterName")); 
    } 
    /* ... and about 15 more of these */ 
} 

CommonView.aspx:

<%-- ... --%> 
<% using (Html.BeginForm(FormMethod.Get)) {%> 
    <%=Html.TextBox(Model.ParameterName)%> 
    <input id="submit" type="submit" value="Submit" /> 
<%}%> 
<%-- ... --%> 

現在還不清楚如何讓文本框按名稱參數綁定回從該觀點不明確創建行動指定它。

回答

0

或者,有沒有辦法讓動作和參數使用。如果你離開的BeginForm參數的動作和控制器部分空來產生這種觀點

,它會回發到哪裏它來自於。只要具有不同的參數,就可以有兩個具有相同名稱的操作,一個裝飾爲HttpGet和另一個HttpPost。通常get有一個或沒有,並且該帖子有幾個或一個模型綁定。

+0

啊,很高興知道。有沒有辦法獲得動作的參數名稱,或者其他方式將文本框綁定到參數? – 2009-11-25 16:24:28

+0

您在返回視圖的操作中定義的模型是THE Model,所以我認爲不需要做任何特殊的事情。 – 2009-11-25 16:36:10