This is giving me a hard time to implement. I've generated a controller and view to handle updating a model.
However in the Create.cshtml I need to add a drop down with database users (using db.Users.Tolist()) to populate the dropdown.
<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>
So I've taken @Html.EditorFor()
and replaced it with @Html.DropDownListFor()
to show the dropdown list. And this does work but I get an error when I click submit.
The ViewData item that has the key 'UserId' is of type 'System.String' but must be of type 'IEnumerable'.
Here's the Model.
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; }
}
And the Create controller.
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);
}
I feel that I'm almost there. But just need a push in the right direction to make this work.