在ASP.NET MVC模式的关系 [英] Model relationships in ASP.NET MVC

查看:76
本文介绍了在ASP.NET MVC模式的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始评估ASP.NET MVC。虽然它是很容易和快速创建模式控制器和视图,只有基本属性(比如从官方网页起动视频所示)我没有找到复杂类型的引用的工作没有什么好的办法。比方说,我有这些型号:

I recently started evaluating ASP.NET MVC. While it is really easy and quick to create Controllers and Views for Models with only primitive properties (like shown in the starter videos from the official page) I didn't find any good way to work with references to complex types. Let's say, I have these Models:

public class Customer {  
    public int Id { get; set; }  
    public string Name { get; set; }  
    public Address Address { get; set; }  
    public IList<Order> Orders { get; set; }  
}

public class Address {  
    public int Id { get; set; }  
    public string .....  
    .....  
}

public class Order {  
    public int Id { get; set; }  
    public Customer Customer { get; set; }  
    public string OrderName { get; set; }  
    .....  
}

请注意,我没有外键的模型(就像是典型的LINQ to SQL的,这也是在样本视频使用),但一个对象引用。

Note that I don't have foreign keys in the models (like it's typical for LINQ to SQL, which is also used in the sample video) but an object reference.

我该如何处理在asp.net的MVC这种提法?是否有人有一些好的建议或链接到这个问题的教程?也许包括复杂类型的自动绑定。

How can I handle such references in asp.net mvc? Does someone has some good tips or links to tutorials about this problem? maybe including autobinding with complex types.

推荐答案

我想一切都合并到我的视图模型:

I would combine everything into my view model:

CustomerViewModel.Customer
CustomerViewModel.Address
CustomerViewModel.Orders // maybe an IEnumerable<Order>
CustomerViewMode.CurrentOrder

您应该可以使用一些输入佣工绑定您的复杂的对象没有太多的麻烦:

You should be able to bind your complex objects without too much trouble using some of the input helpers:

//.. begin form
<%=Html.HiddenFor(m=>m.Customer.Id)%>
<%=Html.TextboxFor(m=>m.Customer.FirstName)%>
<%=Html.TextBoxFor(m=>m.Address.City)%>
<%=Html.TextBoxFor(m=>m.ActiveOrder.OrderName%>
//.. submit ..
//.. end form ..

本应该绑定回ok了,如果你的操作方法如下:

The should bind back ok if your action method looks like:

[HttpPost]
public ActionResult UpdateComplexObject(string id, CustomerViewModel customerViewModel) {
// if (!id.Equals(customerViewModel.Customer.Id) throw something
// just one of my own conventions to ensure that I am working on the correct active
// entity - string id is bound from the route rules.
ValidateModel(customerViewModel);
service.UpdateCustomer(customerViewModel.Customer);
serviceOrder.UpdateOrder(customerViewModel.ActiveOrder);
serviceAddress.UpdateAddress(customerViewModel.Address);
return RedirectToAction("DisplayComplexObject"); // or whatever
}

哈尔

这篇关于在ASP.NET MVC模式的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆