【发布时间】:2011-08-02 10:20:42
【问题描述】:
我有以下动作方法(部分代码):
[HttpPost]
public ActionResult Create(EditGrantApplicationViewModel editGrantApplicationViewModel)
{
if (!ModelState.IsValid)
{
return View("Create", editGrantApplicationViewModel);
}
return View("Index");
}
EditGrantApplicationViewModel 看起来像这样(部分代码):
public class EditGrantApplicationViewModel
{
public IEnumerable<Title> Titles { get; set; }
public int TitleId { get; set; }
public IEnumerable<Bank> Banks { get; set; }
public int BankId { get; set; }
public IEnumerable<AccountType> AccountTypes { get; set; }
public int AccountTypeId { get; set; }
}
当第一次请求这个 Create 视图时,我会在我的服务层中填充 Titles 并返回一个 EditGrantApplicationViewModel 的实例,如下所示:
public ActionResult Create()
{
EditGrantApplicationViewModel editGrantApplicationViewModel = grantApplicationService.CreateEditGrantApplicationViewModel();
return View(editGrantApplicationViewModel);
}
我的服务层中的CreateEditGrantApplicationViewModel:
public EditGrantApplicationViewModel CreateEditGrantApplicationViewModel()
{
EditGrantApplicationViewModel editGrantApplicationViewModel = new EditGrantApplicationViewModel
{
Titles = titleRepository
.GetAll()
.Where(x => x.Active)
.OrderBy(x => x.Name)
};
return editGrantApplicationViewModel;
}
当我单击提交按钮时,它将进入发布操作Create 方法。它接收EditGrantApplicationViewModel 类型的editGrantApplicationViewModel 参数。为什么 Titles 属性设置为 null?我认为它会保留它的价值吗?
现在假设有一个错误,ModelState.IsValid 是错误的。所以这意味着我将不得不重新填充Titles 属性。鉴于已在editGrantApplicationViewModel 的表单中设置的属性值,我现在将如何填充 Titles 属性?我假设我需要在我的服务层中使用另一种方法来填充它?最好的方法是什么?
任何源代码将不胜感激。
2011-04-11 更新
在我看来,我有 3 个下拉菜单。头衔、银行和账户类型。这就是为什么我的视图模型中有 3 个列表。我有一个服务类来处理插入、更新和获取项目。例如,在我的银行服务类中,我会有与银行相关的 Insert、Update、GetAll、GetById 等方法。我会在标题和帐户类型服务中拥有类似的服务。
这是我目前在控制器类中的方式:
private IGrantApplicationService grantApplicationService;
private ITitleService titleService;
private IBankService bankService;
private IAccountTypeService accountTypeService;
public GrantApplicationController(IGrantApplicationService grantApplicationService, ITitleService titleService, IBankService bankService, IAccountTypeService accountTypeService)
{
this.grantApplicationService = grantApplicationService;
this.titleService = titleService;
this.bankService = bankService;
this.accountTypeService = accountTypeService;
}
public ActionResult Create()
{
EditGrantApplicationViewModel editGrantApplicationViewModel = new EditGrantApplicationViewModel
{
// Populate the dropdown lists
Titles = titleService
.GetAll()
.Where(x => x.Active)
.OrderBy(x => x.Name),
Banks = bankService
.GetAll()
.Where(x => x.Active)
.OrderBy(x => x.Name),
AccountTypes = accountTypeService
.GetAll()
.Where(x => x.Active)
.OrderBy(x => x.Name)
};
return View(editGrantApplicationViewModel);
}
我们不久前谈过,您说最好为控制器提供一项服务。就我而言,我需要从 3 个不同的数据库表中填充 3 个列表。您能否提供一些代码来说明您将如何做到这一点。如果需要更多详细信息,请告诉我。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 viewmodel