如何在ASP.NET MVC4中将ViewModel传递给编辑操作
本文关键字:编辑 操作 ViewModel 中将 ASP NET MVC4 | 更新日期: 2023-09-27 18:24:32
我想将ViewModel
传递给MVC4中的编辑操作,这是我为Create
操作创建的,但像初学者一样,我被困在这里。
public class EditEntryViewModel
{
public string Title { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Url { get; set; }
public string Description { get; set; }
}
控制器:
[HttpGet]
public ActionResult Edit(int? entryId)
{
Entry customer = _db.Entries.Single(x => x.Id == entryId);
var customerViewModel = new EditEntryViewModel();
return View(customerViewModel);
}
入门级:
public class Entry
{
[Key]
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual string Url { get; set; }
public virtual string Description { get; set; }
}
您没有设置customerViewModel
的任何属性,因此您的视图不会显示任何数据。基于Entry
类的定义,以下是您的控制器操作方法应该是什么样子的
[HttpGet]
public ActionResult Edit(int? entryId)
{
var customerViewModel = new EditEntryViewModel();
if (entryId.HasValue)
{
Entry customer = _db.Entries.SingleOrDefault(x => x.Id == entryId.Value);
if (customer != null)
{
customerViewModel.Title = customer.Title;
customerViewModel.Username = customer.Username;
customerViewModel.Password = customer.Password;
customerViewModel.Url = customer.Url;
customerViewModel.Description = customer.Description;
}
}
return View(customerViewModel);
}
您发布的操作是显示编辑页面,您需要对它做的只是用id参数调用它,而不要求它提供完整的视图模型
您想保存编辑结果吗?
创建另一个同名操作,但接受带参数的EditEntryViewModel
,只接受[HttpPost]
[HttpPost]
public ActionResult Edit(EditEntryViewModel viewModel)
{
//code here
}