2013-03-13 151 views
-2

我有其中有多個其他模型的模型。綁定多個模型asp,net mvc

public class mainmodel 
{ 
public entity1(); 
public entity2(); 
} 

發佈視圖後,我得到entity1實體null?運氣好的話。我做錯了? 我的問題是:Asp.net with MVC multiple model in one view (create, update) 如何獲取模型中的類實體?

+0

請顯示您的視圖和控制器代碼。 – 2013-03-13 06:54:33

+0

在我看來,我正在渲染通過entity1和entity2的局部視圖。所以我可以在發佈後獲取模型的值 – 2013-03-13 06:55:13

+0

檢查[This](http://stackoverflow.com/questions/15339272/how-to-pass-a-nested-model-value-in-html-partial/15339376#15339376 ) – 2013-03-13 06:58:05

回答

0

控制器(HomeController中):

public ActionResult Index() 
    { 
     mainmodel model=new mainmodel(); 
     return View(model); 
    } 

[HttpPost] 
public ActionResult Index(mainmodel model) 
    { 
     return View(model); 
    } 

視圖(首頁/索引):

@model mainmodel 
@using (Html.BeginForm("Index","Home",FormMethod.Post)) 
{ 
    <input type="submit" value="Submit" /> 
} 
+0

是的,但我有IndexPageViewModel中的另一個類,不管用。 – 2013-03-13 07:25:29

+0

您無法將多個模型與mvc中的一個視圖綁定,因爲它是1:1關係。如果你想這樣做,你必須創建一個ViewModel,其中包含你想要在你的視圖中綁定的模型。請參閱我的下一個答案中的代碼。我希望它有幫助。 – 2013-03-13 08:02:44

0

視圖模型(IndexViewModel):

public class IndexViewModel 
{ 
    public mainmodel model1 {get;set;} 
    public anotherclass model2 {get;set;} 
} 

控制器(HomeController中):

public ActionResult Index() 
{ 
    IndexViewModel model=new IndexViewModel(); 
    return View(model); 
} 

[HttpPost] 
public ActionResult Index(IndexViewModel model) 
{ 
    return View(model); 
} 

視圖(首頁/索引):

@model IndexViewModel 
@using (Html.BeginForm("Index","Home",FormMethod.Post)) 
{ 
    <input type="submit" value="Submit" /> 
} 

現在你可以在HttpPost所有的值。

+0

嗨,上面的作品,但正如我所說,我在部分視圖中傳遞MainViewmodel.Entityclass。 @ Html.Partial(「_ Model1」,Model.MyModel1),它給出了錯誤。傳入字典的模型項目類型爲'MvcApplication1.Models.MainModel',但該字典需要一個'MvcApplication1.Models.Model1'類型的模型項目。 – 2013-03-13 09:17:56

+0

要將哪個模型傳遞到您的部分視圖中,您需要在頁面頂部聲明完全相同的模型(局部視圖)。我認爲您在部分視圖頂部寫入了「@model MvcApplication1.Models.MainModel」而不是「@model MvcApplication1.Models.Model1」,這是錯誤的。請在部分視圖的頂部寫上「@model MvcApplication1.Models.Model1」。 – 2013-03-13 10:02:21