gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 3 多个模型到单个表单

转载 作者:行者123 更新时间:2023-12-04 07:58:42 25 4
gpt4 key购买 nike

我正在学习 ASP.NET MVC 3 并尝试使用单个表单创建一个 View ,该表单由通过外键链接在一起的多个模型组成。最终目标是将单个表单插入到所有数据库表中。

问题是我无法弄清楚为什么当我右键单击以创建 View 时,表单不是在 cshtml 文件中自动生成的。自动生成的代码有很大帮助,因为我有许多链接在一起的表,以及许多必须验证和插入的字段。如果无法自动生成表单,那么完成此任务的最有效/最优雅的方法是什么?

这是我所拥有的简化。

模型:

class Customer
{
[Key]
public UInt64 CustomerId { get; set; }

[Required(ErrorMessage = "Name is required.")]
[Display(Name = "Customer Name")]
[MaxLength(50)]
public string FullName { get; set; }
}

class CustomerAdditionalDetails1
{
[ForeignKey("Customer")]
public UInt64 CustomerId { get; set; }

[Required(ErrorMessage = "This info is required.")]
[Display(Name = "Customer Information")]
[MaxLength(50)]
public string SomeInfo { get; set; }
}

class CustomerAdditionalDetails2
{ // same foreign key as CustomerAddtionalDetails1, but with different properties
}

class CustomerAdditionalDetails3
{ // same foreign key as CustomerAddtionalDetails1, but with different properties
}

...

public class CustomerModel
{
public Customer Customer { get; set; }
public CustomerAdditionalDetails1 CustomerAdditionalDetails1 { get; set; }
public CustomerAdditionalDetails2 CustomerAdditionalDetails2 { get; set; }
public CustomerAdditionalDetails3 CustomerAdditionalDetails3 { get; set; }
...
}

Controller :
public ActionResult Submit()
{
return View();
}

[HttpPost]
public ActionResult Submit(CustomerModel customer)
{
return View();
}

请帮忙!

最佳答案

生成 View 时,是否创建了基于 CustomerModel 的强类型 View ?如果您正在生成 View ,则不会在页面中输出任何值,因为您的所有属性都是对其他对象的引用。您需要模型中包含的实际值类型,以便脚手架自动将它们包含在 View 中。也就是说,您始终可以按照下面的示例自己将它们添加到 View 中。

我还注意到在您的 Controller 中,您的 GET 方法不会将模型返回到要呈现的 View 。如果您想根据模型生成 View ,那么您需要传递您希望它为其生成的对象。

@model MvcApplication3.Models.CustomerModel

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<fieldset>
<legend>CustomerModel</legend>
</fieldset>
<ul>
<li>@Model.Customer.FullName</li>
<li>@Model.CustomerAdditionalDetails1.SomeInfo1</li>
<li>@Model.CustomerAdditionalDetails2.SomeInfo2</li>
</ul>
<p>
@Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
@Html.ActionLink("Back to List", "Index")
</p>


public class CustomerController : Controller
{
public ActionResult Index()
{
CustomerModel customerModel = new CustomerModel()
{
Customer = new Customer()
{
FullName = "Dan"
},
CustomerAdditionalDetails1 = new CustomerAdditionalDetails1()
{
SomeInfo1 = "Somewhere1"
},
CustomerAdditionalDetails2 = new CustomerAdditionalDetails2()
{
SomeInfo2 = "Somewhere2"
},
CustomerAdditionalDetails3 = new CustomerAdditionalDetails3()
{
SomeInfo3 = "Somewhere3"
}
};

return View(customerModel);
}
}

关于asp.net-mvc - ASP.NET MVC 3 多个模型到单个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6087366/

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