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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ASP.NET MVC 3多个模型到单个表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习ASP.NET MVC 3并尝试使用单个表单创建一个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; }
    ...
}

控制器:

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

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

请帮忙!

解决方法

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

另外我在你的控制器中注意到你的GET方法没有将模型返回给要渲染的视图.如果要根据模型生成视图,则需要传递要为其生成的对象.

@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相关文章