MVC 3,DI和视图的最佳实践

时间:2011-09-16 17:33:05

标签: asp.net-mvc-3 view dependency-injection

考虑两个观点。哪个是首选,哪种情况下你会使用样式1而不是样式2,反之亦然?

样式1:查看注入

using System.Web.Mvc;
using Ninject;
namespace Views.Models.ViewClasses {
    public abstract class CalculatorView : WebViewPage {
           [Inject]
           public ICalculator Calulator { get; set; }
    }
}

观点:

 @inherits Views.Models.ViewClasses.CalculatorView
 @{
     ViewBag.Title = "Calculate";
 }
 <h4>Calculate</h4>
 The calculation result for @ViewBag.X and @ViewBag.Y is @Calulator.Sum(ViewBag.X, ViewBag.Y)

样式2:使用模型

public class CalculatorModel {
      // a constructor in here somewhere
      public int X { get; set; }
      public int Y { get; set; }
      public int SumXY { get; set; }
}

控制器:

public class CalculatorController : Controller {
    private readonly ICalculator _calculator;
    [Inject]
    public CalculatorController (ICalculator calculator)  {
           _calculator = calculator;
    }

    public ActionResult Calculate(int x, int y)
    {
        return View(new CalculatorModel(x, y, _calculator.Sum(x, y))
    }
    ...

观点:

 @model CalculatorModel
 @{
     ViewBag.Title = "Calculate";
 }
 <h4>Calculate</h4>
 The calculation result for @Model.X and @Model.Y is Model.SumXY

我真正能想到的是:

  • 如果在视图中需要大量使用计算器或其他任何东西,那么查看注入会更有意义,否则模型会有负载和数据加载,否则应该首选模型?

0 个答案:

没有答案