2016-07-25 32 views
0

這給我很難實現。我已經生成了一個控制器和視圖來處理更新模型。將下拉列表添加到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); 
} 

我覺得我快到了。但只需要朝正確的方向推動這項工作。

+0

請注意,模型 - 視圖 - 控制器標籤是關於模式的問題。 ASP.NET-MVC實現有一個特定的標籤。 –

+0

副本很好地解釋了它:在您的HttpPost操作方法中,如果要再次呈現視圖,則必須再次初始化SelectList。第二段的最後一行:_「如果您返回視圖,則必須先重新分配CategoryList的值,就像您在GET方法中所做的那樣」_「。另外,不要在你的問題中加入關於密切原因的評論,添加評論和@ @通知最近的選民。 – CodeCaster

回答

1

這是你如何讓你的SelectListItems

ViewData["items"] = db.UserProfiles 
    .Select(x => new SelectListItem() { Text = x.UserName, Value = x.UserId.ToString() }); 

這是你將如何使用它

@Html.DropDownListFor(model => model.UserId, ViewData["items"] as IEnumerable<SelectListItem>) 
+0

這當然完美地填充列表。然而,當點擊提交我仍然得到。 {「具有'UserId'鍵的ViewData項的類型是'System.String',但是必須是'IEnumerable '的類型。」}是否需要改變控制器文章中的內容? – Prescient

+0

@Prescient 您可能需要創建一個新模型,僅用於顯示將UserId作爲字符串(視圖模型,如果您願意)的視圖。然後,您必須更改Create方法以將db模型轉換爲視圖模型,然後更改您的CreatePost方法以將其轉換回您的db模型。也可能有另一種更簡單的方法。我不會使用剃刀。 –

0

我從來沒有嘗試直接傳遞selectlistitem收集到的頁面。我通常會將該列表添加到模型中,然後使用剃鬚刀創建一個新的selectlistitem集合。

您是否有選擇修改模型?

@Html.DropDownListFor(model => model.UserId, Model.availableUsers.Select(user => new SelectListItem() { Text = user.displayVariable, Value = user.userId, Selected = user.userId == model.UserId }).ToArray()) 
相關問題