![](/img/trans.png)
[英]Gracefully handling HTML tags on form submission in asp.net MVC 2
[英]Handling MVC form submission to database
因此,我大致上遵循“音樂商店”教程。 我在pg上創建了StoreManagerController。 54ish。 然后使用“創建”,“刪除”,“編輯”等方法創建了一個視圖。它將某些內容保存到數據庫中,即我的EditFor控件,但沒有其他內容。
我有多個DropDownListFor控件,分別由數據庫中的兩個表以及Active Directory用戶數據填充。 我不確定如何保存這些文件。 這是我的簡化代碼。 謝謝您的幫助。
視圖:
<div class="createTopInner">
<div class="editor-label">
@Html.LabelFor(model => model.test.Category)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CategoryId, Model.CategoryItems, "")
@Html.ValidationMessageFor(model => model.test.Category)
</div>
</div>
控制器:
public ActionResult Create()
{
// These four lines get active directory users
ActiveDirectoryModel ads = new ActiveDirectoryModel();
ViewBag.assignedto = ads.FetchContacts();
ViewBag.coassignedto = ads.FetchContacts();
ViewBag.notifyto = ads.FetchContacts();
var model = Populate();
return View(model);
}
[HttpPost]
public ActionResult Create(CreateViewModel model)
{
if (ModelState.IsValid)
{
db.TestItems.AddObject(model.test);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
public CreateViewModel Populate()
{
var model = new CreateViewModel
{
CategoryItems =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
}
};
return model;
}
模型:
public class CreateViewModel
{
public Intra.Models.TestItem test{ get; set; }
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryItems { get; set; }
}
如果您可以訪問它/對存儲過程了解很多,最好在數據庫中使用存儲過程,然后在Entity中調用它們。 它更加松散耦合,並且無需重新編譯代碼即可更輕松地進行更改。
問題似乎是,盡管您的大多數輸入都映射到test
屬性,但CategoryId
卻沒有。 一無所知,很難說,但我冒昧地猜測您需要從數據庫中檢索相應的Category
並將其添加到TestItem
實例中,然后再進行持久化。 如果您確實在TestItem
實例上具有CategoryId
屬性,則可以對其進行設置,但是我猜您沒有設置它,因為否則您將直接使用它(就像對Category
標簽所做的那樣)而不是添加屬性到視圖模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.