這給我很難實現。我已經生成了一個控制器和視圖來處理更新模型。將下拉列表添加到mvc頁面
但是在Create.cshtml中,我需要向數據庫用戶添加一個下拉列表(使用db.Users.Tolist())來填充下拉列表。
<div class="form-group">
@Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
// @Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control" } })
@Html.DropDownListFor(model => model.UserId, ViewData["u"] as IEnumerable<SelectListItem>)
</div>
</div>
所以我已經採取@Html.EditorFor()
和替換它與@Html.DropDownListFor()
以顯示下拉列表。這確實有用,但是當我點擊提交時我收到一個錯誤。
具有鍵'UserId'的ViewData項目類型爲'System.String',但必須是'IEnumerable'類型。
這裏是模型。
public class pdf
{
[Key]
public int ID { get; set; }
public string UserId { get; set; }
public Guid FileGuid { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
}
並創建控制器。
public ActionResult Create()
{
if (ModelState.IsValid)
{
var u = db.Users.Select(x => new { UserId = x.Id, UserName = x.UserName }).ToList();
//u[0].UserName
ViewBag.userinfo = new System.Web.Mvc.MultiSelectList(u, "UserId", "UserName");
IEnumerable<SelectListItem> u1 = new SelectList(db.Users.ToList(), "Id", "UserName");
ViewData["u"] = u1;
}
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,UserId,FileGuid,FileName,FileLocation")] pdf pdf)
{
if (ModelState.IsValid)
{
db.tblPDF.Add(pdf);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pdf);
}
我覺得我快到了。但只需要朝正確的方向推動這項工作。
請注意,模型 - 視圖 - 控制器標籤是關於模式的問題。 ASP.NET-MVC實現有一個特定的標籤。 –
副本很好地解釋了它:在您的HttpPost操作方法中,如果要再次呈現視圖,則必須再次初始化SelectList。第二段的最後一行:_「如果您返回視圖,則必須先重新分配CategoryList的值,就像您在GET方法中所做的那樣」_「。另外,不要在你的問題中加入關於密切原因的評論,添加評論和@ @通知最近的選民。 – CodeCaster