我有一個ViewModel包含一個文本框和下拉框,我想將數據保存到MVC3中的數據庫。ViewModel保存數據
我通常做財產以後這樣的:
if (ModelState.IsValid)
{
db.Orders.Add(orders);
db.SaveChanges();
return RedirectToAction("Index");
}
我怎麼會做這種用於保存視圖模型?
由於提前
編輯 好了,所以IV得到這個視圖模型:
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();
}
}
}
我將如何保存這些數據?四,一旦得知這個話,我可以把它應用到實際場景
感謝
只是爲了澄清,你是說通常你會直接接受你的數據庫對象類型的模型,這次你不是? – DMulligan 2012-04-23 00:27:42
@ AFinkelston即將做的事是按照這個教程http://codeoverload.wordpress.com/2011/05/22/dropdown-lists-in-mvc-3/但我不知道如何保存seleced值,因爲它使用ViewModel,我從來沒有用過,因爲我是MVC3的新手。 – user1302054 2012-04-23 00:33:08