C#MVC:使用Modelbinders有哪些真正的优势?

时间:2009-06-07 00:57:52

标签: c# asp.net-mvc

我想知道使用Modelbinders的真正可测量优势是什么?

3 个答案:

答案 0 :(得分:1)

而不是将原语发送到您的操作中:

public ActionResult Search(string tagName, int numberOfResults)

你得到一个自定义对象:

public ActionResult Search(TagSearch tagSearch)

这使您的搜索操作“更薄”(一件好事),更加可测试并减少维护。

答案 1 :(得分:0)

  

模型粘合剂

     

MVC中的模型绑定器提供了一个   映射已发布表单值的简单方法   到.NET Framework类型并传递   键入动作方法作为   参数。宾德斯也给你了   控制反序列化   传递给action的类型   方法。模型粘合剂就像类型   转换器,因为它们可以转换   HTTP请求进入对象   传递给一个动作方法。然而,   他们也有关于的信息   当前的控制器背景。

来自here

答案 2 :(得分:0)

这是另一个好处:

您可以创建仅在给定ID的情况下从数据库中检索对象的模型绑定器。

这将允许您进行此类操作

// GET /Orders/Edit/2
public ActionResult Edit(Order order){
  return View(order);
}

自定义ModelBinder会为您进行数据提取,让您的控制器变得粗糙。

如果没有ModelBinder,它可能看起来像这样:

// GET /Orders/Edit/2
public ActionResult Edit(int id){
  var order = _orderRepository.Get(id);
  // check that order is not null and throw the appropriate exception etc
  return View(order);
}
相关问题