我有一个包含文本框和下拉框的 ViewModel,我想将数据保存到 MVC3 中的数据库中。
我通常会这样做:
if (ModelState.IsValid)
{
db.Orders.Add(orders);
db.SaveChanges();
return RedirectToAction("Index");
}
我将如何保存 ViewModel?
提前致谢
编辑好的,所以我得到了这个 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学会了这一点,我就可以将其应用于实际场景
谢谢