ViewModel保存数据

时间:2012-04-23 00:09:14

标签: visual-studio-2010 asp.net-mvc-3 model code-first

我有一个包含文本框和下拉框的ViewModel,我想将数据保存到MVC3中的数据库。

我通常喜欢这样的事情:

if (ModelState.IsValid)
{
    db.Orders.Add(orders);
    db.SaveChanges();
    return RedirectToAction("Index");  
}

如何保存ViewModel?

先谢谢

EDIT 好的,所以我得到了这个ViewModel:

namespace DropDownList.Models
{
public class CreditCardModel
{
public List<SelectListItem> CardTypeOptions { get; set; }

[Display(Name = "Card Type")]
public string CardTypeID { get; set; }

[Display(Name = "Card Number")]
[Required(ErrorMessage = "Please provide your card number")]
public string CardNumber { get; set; }
}
}

and this controller:
namespace DropDownList.Controllers
{
public class CreditCardModelController : Controller
{
//
// GET: /CreditCardModel/
public ActionResult Index()
{
var model = new CreditCardModel();
// Populate the dropdown options
model.CardTypeOptions = GetCardTypes("MS"); // Set the default to American Express

return View(model);
}

[HttpPost]
public ActionResult Index(CreditCardModel model)
{
if (ModelState.IsValid)

{
return RedirectToAction("addcardcomplete");
}
// TODO - Handle the form submit
// Populate the dropdown options
model.CardTypeOptions = GetCardTypes("MS"); // Set the default to American Express

return View(model);
}
// TODO - AddCardComplete goes here



// TODO - GetCardTypes goes here

private List<SelectListItem> GetCardTypes(string defaultValue)
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "American Express", Value = "AE", Selected = (defaultValue == "AE") });
items.Add(new SelectListItem { Text = "Mastercard", Value = "MS", Selected = (defaultValue     == "MS") });
items.Add(new SelectListItem { Text = "Visa", Value = "VS", Selected = (defaultValue == "VS") });
return items;
}

public ActionResult AddCardComplete()
{
return View();
}
}
}

我如何保存这些数据?一旦iv学会了这一点,我就可以将它应用到真实场景

由于

2 个答案:

答案 0 :(得分:2)

创建实体模型的实例,并从ViewModel中设置您正在读取的值,该ViewModel将发布到action方法并用于保存到数据库。有点像这样。

[HttpPost]
public ActionResult SaveOrder(OrderViewModel orderVM)
{
  if(ModelState.IsValid)
  {
    YourDomainEntity objDomainModel=new YourDomainEntity();
    objDomainModel.ItemId=orderVm.ItemId;
    objDomainModel.Quantity=orderVM.Quantity;
    //Set Other relevant properties also

    db.Orders.Add(orders);
    db.SaveChanges();
    return RedirectToAction("Index"); 

  } 
}

您可以考虑将AutoMapper等库从您的域对象映射到ViewModel。

答案 1 :(得分:0)

我认为你的意思是编辑?您可以将其重新附加为已修改并重新保存..

db.Orders.Attach(orders, true);
db.ObjectStateManager.ChangeObjectState(orders, EntityState.Modified);
db.SaveChanges();

虽然我强烈建议您拆分数据库对象和视图模型。您还可以使用AutoMapper使来回生活变得更轻松,但保持数据库和前端分离。