我一直在MVC最近工作,我很好奇初始化我的視圖模型的最佳方式是什麼。我應該直接在控制器中映射它,還是應該在視圖模型的構造函數中初始化屬性。另外,當有列表時,這是更好的做法,因爲當出現驗證錯誤時,您不必重新填充它們。.NET MVC3優先模型初始化
舉例來說,如果我有以下型號:
public FooBarViewModel
{
public int FooBarId { get; set; }
public string SomeInitialProperty1 { get; set; }
public string SomeInitialProperty2 { get; set; }
public string SomeInitialProperty3 { get; set; }
public string SomeInitialProperty4 { get; set; }
public int FooId { get; set; }
public int BarId { get; set; }
public IEnumerable<Foo> Foos { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
,然後控制器:
public MyController : Controller
{
[HttpGet]
public ActionResult FooBar(int foobarId)
{
var foobar = _fooBarRepository.GetById(foobarId);
var model = new FooBarViewModel
{
FooBarId = foobar.Id;
SomeInitialProperty1 = foobar.SomeInitialProperty1;
SomeInitialProperty2 = foobar.SomeInitialProperty2;
SomeInitialProperty3 = foobar.SomeInitialProperty3;
SomeInitialProperty4 = foobar.SomeInitialProperty4;
Foos = foobar.Foos.ToList();
Bars = foobar.Bars.ToList();
}
return View(model);
}
[HttpPost]
public ActionResult FooBar(FooBarViewModel model)
{
if (ModelState.IsValid)
{
//process model
return RedirectToAction("Index");
}
var foobar = _fooBarRepository.GetById(model.FoobarId);
model.Foos = foobar.GetFoos.ToList();
model.Bars = foobar.GetBars.ToList();
return View(model);
}
}
或者我應該做它在我的模型:
public FooBarViewModel
{
public int FooBarId { get; set; }
public string SomeInitialProperty1 { get; set; }
public string SomeInitialProperty2 { get; set; }
public string SomeInitialProperty3 { get; set; }
public string SomeInitialProperty4 { get; set; }
public int FooId { get; set; }
public int BarId { get; set; }
public IEnumerable<Foo> Foos
{
get { return _foos; }
}
private IEnumerable<Foo> _foos;
public IEnumerable<Bar> Bars
{
get { return _bars; }
}
private IEnumerable<Bar> _bars;
public MyViewModel(FooBar foobar)
{
FooBarId = foobar.Id;
SomeInitialProperty1 = foobar.SomeInitialProperty1;
SomeInitialProperty2 = foobar.SomeInitialProperty2;
SomeInitialProperty3 = foobar.SomeInitialProperty3;
SomeInitialProperty4 = foobar.SomeInitialProperty4;
_foos = foobar.Foos.ToList();
_bars = foobar.Bars.ToList();
}
}
然後我的控制器:
public MyController : Controller
{
[HttpGet]
public ActionResult FooBar(int foobarId)
{
var foobar = _fooBarRepository.GetById(foobarId);
var model = new FooBarViewModel(foobar);
return View(model);
}
[HttpPost]
public ActionResult FooBar(FooBarViewModelmodel)
{
if (ModelState.IsValid)
{
//process model
return RedirectToAction("Index");
}
return View(model);
}
}
這是MVC中的首選約定,爲什麼它是最佳實踐?另外,爲什麼選擇一個在另一個之上的原因?提前致謝。
對於AutoMapper爲+1。在這裏學到了新東西。 –
這看起來像一個很好的解決方案,看起來會節省時間。我將在我的項目中看看這個實現。謝謝。 – shuniar