2012-07-16 44 views
1

我有一個MVC 3項目,我開始使用c#和Razor。我有一個頁面,有大約20個輸入字段將被使用。我創建我的ViewModel將數據傳遞給視圖來創建頁面。我很困惑,當用戶提交表單時,我如何獲得字段的值。如何檢索MVC上所有輸入的所有值

我的控制器是否必須爲我的頁面上的每個輸入字段都有一個參數?有沒有辦法讓Controller獲取頁面上的所有數據,然後我可以通過它解析?參數列表將是巨大的。

回答

3

您可以使用與傳遞給視圖相同的模型作爲後續操作中的參數。

一個例子:

//This is your initial HTTP GET request. 
public ActionResult SomeAction() { 
    MyViewModel model; 

    model = new MyViewModel(); 
    //Populate the good stuff here. 

    return View(model); 
} 

//Here is your HTTP POST request; notice both actions use the same model. 
[HttpPost] 
public ActionResult SomeAction(MyViewModel model) { 
    //Do something with the data in the model object. 
} 

在第二方法中的模型對象將自動從包含在HTTP請求中的數據填充(技術名稱是「模型綁定」)。

0

請創建在您的控制器的MVC動作取模型參數

Like this: 

[HttpPost] or [HttpGet] 
public ActionResult Employee(EmployeeModel employee) 
{ 
// now you will have all the input inside you model properties 
//Model binding is doen autoamtically for you 
} 
2

在你的控制器的行動,希望得到同樣的「樣板」你回傳給視圖。如果您正確地生成了「輸入控件」(通過使用Html.TextBoxFor()或將Name屬性設置爲與您的模型屬性相同的名稱),這將起作用。

public ActionResult MyAction(MyViewModel model) 
{ 
... 
} 

注意MVC將使用ModelBinder的弄清楚如何創建和填寫你的行動是基於從用戶提交的領域預期對象的屬性。

如果你想捕捉來自用戶所有輸入,你可以讓你的行動來獲得FormCollection類型的對象:

public ActionResult MyAction(FormCollection values) 
{ 
... 
}