簡體   English   中英

如何在剃刀MVC asp.net中組合兩個視圖模型

[英]How to combine two view models in razor MVC asp.net

可以說我有一些模型如下:

public class Model1 
{
   public int ID{get;set;}
   public string Name{get;set;}
}

public class Model2 
{
    public int ID{get;set;}
    public string Name{get;set;}
}

class CommonViewModel 
{
    public string Title{get;set;}
    public Model1 model1;
    public Model2 model2;
}

我有一個剃刀觀點如下

@model ProjectName.CommonViewModel

@Html.LabelFor(m => model.Title)           
@Html.EditorFor(m => model.Title)

@Html.LabelFor(m => model.model1.Name)           
@Html.EditorFor(m => model.model1.Name)

在我的控制器上我有一個回傳,它將CommonViewModel作為參數。 公共視圖模型將具有Title的值,但不具有model1.Name的值。 為什么以及如何將該值存儲並在帖子中發送回控制器。

您的CommonViewModel類存在一些問題。 它應該是公共的,model1和model2應該有getter和setter:

public class CommonViewModel
{
    public string Title { get; set; }
    public Model1 model1{get;set;}
    public Model2 model2{get;set;}
}

同樣在視圖中您需要修復:

@Html.LabelFor(m => m.Title)           
@Html.EditorFor(m => m.Title)

@Html.LabelFor(m => m.model1.Name)           
@Html.EditorFor(m => m.model1.Name)

上面的代碼在我的測試中運行良好。

您需要在控制器中使用兩種方法:一種用於POST,另一種用於GET。

由於您希望保留模型中存儲的值,因此必須將它們從POST方法傳遞給GET方法。 您還必須在view指定POST。 以下是關於代碼如何在控制器中的概念。 我沒試過這個,所以我只是在這里:

[HttpPost]
public ViewResult PostActionMethod(CommonViewModel commonViewModel)
{
   if (ModelState.IsValid)
   {
       //your code follows
   }

   return RedirectToAction("GetActionMethod", commonViewModel);
}

[HttpGet]
public ViewResult GetActionMethod(CommonViewModel commonViewModel)
{
   //your code follows

   return View(commonViewModel);
}

希望這可以幫助!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM