2011-03-18 80 views
0

我在UI了很多場的,當我發佈從爲「myController的」動作「插入」ASP.NET MVC節省很多場從UI

我必須這樣做:

public ActionResult Insert(string fieldA, string FieldB, int age, .....) 
{ 
} 

有另一種方式,從形式獲得價值? (使用ASP.NET MVC3)我有大約20場,以節省....

感謝,

回答

2

試圖通過改爲調用模型綁定的概念,利用一個ViewModel的。

下面是我用一個例子:

public ActionResult Create() { 
    return View(new MyCreateViewModel()); 
} 

[HttpPost] 
public ActionResult Create(MyCreateViewModel viewModel) 
{ 
    try 
    { 
     db.Save(viewModel); 
     return RedirectToAction("Index"); 
    } 
    catch(Exception ex) 
    { 
     ViewData.ModelState.AddModelError(string.Empty, ex.Message); 
     return View(); 
    } 
} 

和視圖模型是這樣的:

public class MyCreateViewModel { 
    public string MyProperty { get; set; } 
} 

有了這個,我使用的是採用MyCreateViewModel和一個強類型的視圖在查看我利用@Html.EditorFor(m => m.MyProperty)編輯的字段。

1

你可以使用一個輸入模型,這基本上是一個POCO爲每個字段屬性。事情是這樣的:

class InsertInputModel 
{ 
    public string Field1 {get; set; } 
    public string Field2 {get; set; } 
    ... 
} 

然後你只接受InputModel在你的控制器動作,就像這樣:

public ActionResult Insert(InsertInputModel model) 
+0

不知道我明白。在UI頁面中,我顯示模型中的一些數據。其中值是節目的Html.Textbox沒有比模型的屬性相同的名稱。我能怎麼做 ? – 2011-03-18 14:46:05

0

它們合併成一個模型,或只採取在的FormCollection

public ActionResult Insert(MyCustomModel model) 
{ 
    // model.FieldA 
}  

public ActionResult Insert(FormCollection form) 
{ 
    var fieldA = form["fieldA"]; 
} 
+0

選項1,如果他們能在邏輯上劃分成一個模型,否則,只要使用的FormCollection。 – 2011-03-18 15:10:00