如何将ViewModel传递给ASP.NET MVC4中的编辑操作

时间:2014-09-26 10:11:46

标签: c# asp.net-mvc asp.net-mvc-4

我想将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; }

}

2 个答案:

答案 0 :(得分:1)

您未设置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);
}

答案 1 :(得分:0)

您发布的操作用于显示编辑页面,您需要执行的操作仅使用id参数调用它,并且不会要求您提供完整的视图模型

猜猜你要保存编辑结果吗?

使用相同名称创建另一个操作,但接受带有参数的EditEntryViewModel并仅接受[HttpPost]

[HttpPost]
public ActionResult Edit(EditEntryViewModel viewModel)
{
//code here  
}