Krasimir
Krasimir

Reputation: 259

dropdownList insert NULL

I search a lot here and find something like this to make dropdown list

this is my controller: This pass my data for dropDownList...

public ActionResult Create()
{
    var dba = new WHFMDBContext();
    var query = dba.Categories.Select(c => new { c.Id, c.Name });
    ViewBag.Id = new SelectList(query.AsEnumerable(), "Id", "Name", 3);
    return View();
}




[HttpPost]
        [InitializeSimpleMembership]
        public ActionResult Create(Profits profits)
        {
            var user = db.UserProfiles.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId);
            var profit = new Profits
            {
               Value= profits.Value,
               Description = profits.Description,
               DateInput =profits.DateInput,
               CategoryName =profits.CategoryName,// ???
                User = user,

            };
            db.Profits.Add(profit);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

My View :

@model WebHFM.Models.Profits



@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Profits</legend>

        <div class="editor-field">
           @Html.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--") 
            </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CategoryName.Id)
            @Html.ValidationMessageFor(model => model.CategoryName.Id)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Value)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Value)
            @Html.ValidationMessageFor(model => model.Value)
        </div>...

This insert data to database but CategoryName_Id is NULL what am I missing ? and CategoryName =profits.CategoryName this is a foreign key to Categories in Profits public Categories CategoryName { get; set; }

Upvotes: 0

Views: 490

Answers (1)

Michael Dunlap
Michael Dunlap

Reputation: 4310

Call .ToString() on your Id

model.CategoryMenu = db.Categories.Select(c => new SelectListItem {
                                                    Text = c.Name,
                                                    Value = c.Id.ToString(),
                                                   }
                                          );

Upvotes: 5

Related Questions