简体   繁体   English

使用模型绑定器在ASP.NET MVC中往返查看数据

[英]Round-tripping view data in ASP.NET MVC while using Model Binders

Let's say I have a form with the following "business object" in mind: 假设我有一个考虑以下“业务对象”的表单:

public class MyObject
{
    public string Name { get; set; }
    public User OtherUser { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
}

When the user enters data into any of the fields, I need to round-trip what they entered in order to allow them to correct any fat-fingerings and the like, without having to retype their response. 当用户在任何字段中输入数据时,我需要往返输入他们所输入的内容,以允许他们纠正任何胖手指等,而不必重新输入他们的回答。

Because I cannot round-trip a value like 'Feb 31, 2011' in a DateTime field, I end up using an View Model object like this: 因为我无法在DateTime字段中往返传递“ 2011年2月31日”之类的值,所以最终使用了这样的View Model对象:

public class MyObjectViewModel
{
    public string Name { get; set; }
    public string OtherUserName { get; set; }
    public string CreateDate { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }
}

Ok, all is fine and dandy, I can get this to render exactly the same as the bare business object and the values round-trip when using the following pattern: 好的,一切都很好,我可以使用以下模式将其呈现为与裸业务对象和值往返完全相同:

public ActionResult Create(FormCollection form)
{
    var model = new MyObjectViewModel();
    if (TryUpdateModel(model, form) && ModelState.IsValid)
    {
         // ...
    }

    return View(model);
}

I having the following questions: 我有以下问题:

  1. What is the cleanest way to get the data out of the View Model and into the Business Object? 什么是将数据从View Model移入Business Object的最干净方法? (ie What fills out the rest of the method above?) (即,什么填充了以上方法的其余部分?)
  2. Can I reduce the duplication of field names between the objects, so as to consolidate my changes? 我可以减少对象之间字段名称的重复,以合并更改吗?
  3. In the above example, the field OtherUserName is a string that needs to be converted into a User object. 在上面的示例中,字段OtherUserName是需要转换为User对象的string Whose responsibility is this? 这是谁的责任? The Controller? 控制器? The ViewModel? ViewModel? A model binder? 模型粘合剂?
  1. AutoMapper 自动贴图
  2. You don't need to. 不用了
  3. The mapper 映射器

Example: 例:

[HttpPut]
public ActionResult Create(MyObjectViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        // there are validation errors => redisplay the view
        return View(viewModel);
    }
    var model = Mapper.Map<MyObjectViewModel, MyObject>(viewModel);
    _repository.DoSomethingWithTheModel(model);
    return RedirectToAction("Success")
}

Your problem is caused mostly by allowing the view model to contain invalid data. 您的问题主要是由允许视图模型包含无效数据引起的。 Use the same strong type on your view model as on your data class, add a little javascript validation and "Feb 31" will never make it to the server. 在视图模型上使用与数据类相同的强类型,并添加一些javascript验证,“ 2月31日”将永远不会进入服务器。 Parsing the types is definitely the responsibility of the model binder - you don't need to do anything, your controller action just gets passed a strongly typed model object. 解析类型绝对是模型绑定程序的责任-您无需执行任何操作,您的控制器操作只需传递一个强类型模型对象即可。 User may be a little different though - the primary difference may be that your viewmodel has a field named username and the data model needs a user object with information that wasn't on the form. 但是用户可能有所不同-主要区别可能是您的视图模型具有一个名为用户名的字段,而数据模型需要一个用户对象,该用户对象的信息不在表单上。 Your controller would need to fetch/create the appropriate user object and add it to the data class. 您的控制器将需要获取/创建适当的用户对象,并将其添加到数据类中。

You will still have some validation happening server side after the model is parsed, but that will be the more custom stuff like checking that fields are consistent with each other rather than simple string format issues. 解析模型后,您仍将在服务器端进行一些验证,但这将是更自定义的工作,例如检查字段彼此是否一致,而不是简单的字符串格式问题。

For reducing duplication, I posted my style of models on another question - asp.mvc model design 为了减少重复,我在另一个问题上发布了我的模型样式-asp.mvc模型设计

1) You can strongly type your view so that the view passes the controller a "MyObject" type. 1)您可以强烈键入视图,以便该视图将控制器传递给“ MyObject”类型。 2) Not sure I understand what you are asking 3) Why not make this field an ID that contains the foreign key of the linked ID? 2)不确定我是否理解您的要求3)为什么不将此字段设置为包含链接ID的外键的ID?

Also - there is no reason why a datetime field cant be passed to the view and back left as is. 另外-没有理由不能将datetime字段传递到视图并按原样返回左。 You don't need to pass it as a string and convert. 您无需将其作为字符串传递并进行转换。

PS - I'd recommend looking at this tutorial - should clarify my answers for you. PS-我建议您看一下本教程-应该为您阐明我的答案。

http://www.asp.net/mvc/videos/what-is-aspnet-mvc-80-minute-technical-video-for-developers-building-nerddinner http://www.asp.net/mvc/videos/what-is-aspnet-mvc-80-minute-technical-video-for-developers-building-nerddinner

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM