Krasimir
Krasimir

Reputation: 259

mvc4 dropdownList insert NULL

I search a lot here and find something like this to make dropdown list
this is my model :

public class Profits
    {
        [Key]
        public int Id { get; set; }
        public double Value { get; set; }
        public string Description{ get; set; }
       [DataType(DataType.Date)]
        public DateTime DateInput { get; set; }
        public UserProfile User { get; set; }
        public Categories CategoryName { get; set; }//foreign key
          public   int CategoryID { get; set; }
    }

 public class Categories
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string  Name { get; set; }
        public UserProfile User { get; set; }


    }

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.LabelFor(model => model.CategoryName)
        </div>
    <div class="editor-field">
         @Html.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--") 
        @Html.ValidationMessageFor(model => model.CategoryName)
    </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: 1986

Answers (3)

Komengem
Komengem

Reputation: 3764

This is what i would suggest without looking at your model. PopulateCategoriesDropDownList lives in the same controller as your create action

private void PopulateCategoriesDropDownList(object selectedCategories = null)
    {
        var categoriesQuery = from d in _dataSource.Categories
                         orderby d.Name
                         select d;
        ViewBag.CategoryId= new SelectList(categoriesQuery, "CategoryId", "Name", selectedCategories);
    }

Then your action like this.

    [HttpGet]
    public ActionResult Create()
    {
      PopulateCategoriesDropDownList();
    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();
        PopulateCategoriesDropDownList(profit.CategoryId);
       return View(profit);
    }

In your View:

<div class="editor-label">
            @Html.LabelFor(model => model.CategoryId, "Pick Category")
    </div>
    <div class="editor-field">
        @Html.DropDownList("CategoryId", String.Empty)
        @Html.ValidationMessageFor(model => model.CategoryId)
    </div><br/>

Upvotes: 0

Mike C.
Mike C.

Reputation: 3114

Modify your profits class, add this:

Profits
{
  int CategoryID {get;set;}
}

modify your cshtml. Change

@Html.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--") 

to

@Html.DropDownList("CategoryID", (SelectList) ViewBag.Id, "--Select One--") 

alter your controller:

public ActionResult Create(Profits profits)
        {
            var user = db.UserProfiles.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId);
            var category = db.Categories.FirstOrDefault(o => o.CategoryId == profits.CategoryID);
            var profit = new Profits
            {
               Value= profits.Value,
               Description = profits.Description,
               DateInput =profits.DateInput,
               CategoryName = category,
               User = user
            };
            db.Profits.Add(profit);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

What this will do is change your dropdownlist to return the selected CategoryID. The markup will look like:

<select name="CategoryID" />

On your postback, this will bind to your new Profits.CategoryID. You then use that to make a datbase query to get the selected category object which you then assign to Profits.CategoryName.

Upvotes: 1

Ahmed AlShahawi
Ahmed AlShahawi

Reputation: 1

Your Create() Action Return return View(); without passing the model into view method parameters .

Upvotes: 0

Related Questions