开发者

MVC 3, DI, And Best Practices With Views

开发者 https://www.devze.com 2023-04-05 22:58 出处:网络
Consider the two views. Which is preferred and what is a situation where you would use style 1 and not style 2 and vice versa?

Consider the two views. Which is preferred and what is a situation where you would use style 1 and not style 2 and vice versa?

Style 1 : View Injection

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

And the view:

 @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)

Style 2: Using a Model

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

The Controller:

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

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

The view:

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

All I can really think of is:

  • If the calculator or whatever needs to be used a lot in the view, then view injection makes more sense as otherwise the model would have loads and loads of data otherwise models should be preferred?
0

精彩评论

暂无评论...
验证码 换一张
取 消