【发布时间】:2026-01-19 10:35:01
【问题描述】:
我最近一直在 MVC 中工作,我很好奇初始化我的视图模型的最佳方法是什么。我应该直接在控制器中映射它,还是应该在视图模型的构造函数中初始化属性。此外,当有列表时,这是更好的做法,因为当出现验证错误时您不必重新填充它们。
例如,如果我有以下模型:
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 中的首选约定,为什么它是最佳实践?另外,为什么选择一个而不是另一个?提前致谢。
【问题讨论】:
标签: c# .net asp.net-mvc asp.net-mvc-3