gpt4 book ai didi

asp.net - 如何在索引和编辑 View (强绑定(bind))中传递和合并 MVC3 中的两个模型?

转载 作者:行者123 更新时间:2023-12-04 06:10:29 25 4
gpt4 key购买 nike

模型/数据库实体关系(基线占位符文学内容):

public class TitlePercent
{
public int TitleName;
public decimal Percentage;
}

public class TitleMonthly
{
public string Month;
public int Val;
}

基数 => 1 TitlePercent 到 * TitleMonthly

图解 View (建议):
_____________________________
Name | % || Jan | Feb |
_____________________________
Title1 2% 23 343
Title2 3% 343 3434
_____________________________

Controller (建议):
    // Need view and edit   
public ViewResult ViewTitlePercentAndTitleMontly()
{
return View(db.<NotSureWhatWouldGoHere>.ToList());
}

public ActionResult EditTitlePercentAndTitleMontly(int id)
{
return View(db.<NotSureWhatWouldGoHere>.Find(id));
}

Razor View(建议的伪):
...查看和编辑
@model MVC3.Models.TitlePercent
@model2 MVC3.Models.TitleMonthly
1. For Index View to show the grid not sure how to mash this up (like the grid)
- Perhaps build this in the controller but not sure how to build and pass that to the view as
I have had not dealt with multiple models as relationships.
2. For Edit View need to figure out how to bind to a model similar to:
@Html.EditorFor(model => model.TitleName)
@Html.EditorFor(model => model.Percentage)

foreach TitleMonthly in TitlePercentag
{
@* Iterate and bind somehow *@
@Html.EditorFor(model2 => model2.Month)
@Html.EditorFor(model2 => model2.Val)
}
???

抱歉缺少细节和伪代码,但我只是不必处理多个模型,特别是如果它们彼此相关/依赖,并且可以通过连接的类/表创建 GridView ......那么如果你想编辑一行(两个类的组合,那么如何基于这两个类模型将所有关系绑定(bind)到文本框)?

再次,我将对此进行 mock ,但任何信息和示例将不胜感激。

最佳答案

通常你使用一个叫做 ViewModel 的东西。这是一个为 View 设计的非常具体的模型。您将使用数据模型中的信息填充该模型,然后将其传递给 View 。它不必具有 1:1 的结构,这可以让您拥有更多或更少的信息,具体取决于您的需要。

对于您的编辑器模型,您可以创建类似于以下内容的 ViewModel:

public class TitleEditingViewModel { 
public TitlePercent TitlePercent {get;set;}
public ICollection<TitleMonthly> MonthlyTitles {get;set;}
}

然后,您可以根据需要在 Controller 中填充该模型,然后将模型传递到 View 中。
@Html.EditorFor(model => model.TitlePercent.TitleName)
@Html.EditorFor(model => model.TitlePercent.Percentage)

@foreach titleMonthly in Model.MonthlyTitles {
@Html.EditorFor(model => titleMonthly.Month)
@Html.EditorFor(model => titleMonthly.Val)
}

关于asp.net - 如何在索引和编辑 View (强绑定(bind))中传递和合并 MVC3 中的两个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7846113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com