0

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; }

5
  • the problem is : i see data from db.Categories in my dropdownlist but when i choose some option from this ddl and add some value for others Component (from EditorFor) .They have inserted into DB without choosen category from ddl instead category i have NULL.Thanks for patience Commented Mar 5, 2013 at 21:06
  • Does your profits class have CategoryName or CategoryID. In your example it is CategoryName, but what you are setting your dropdownlist to return is Id? Commented Mar 5, 2013 at 21:13
  • Is Categories CategoryName a list of categories, or a single category? Commented Mar 5, 2013 at 21:28
  • I'm going with that meaning it is a single category object. Commented Mar 5, 2013 at 21:40
  • @user2026573 I can answer this question but i need to know how your model is set up. Commented Mar 5, 2013 at 21:52

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Ok I see now. You can replace your @Html.EditorFor() with @Html.Textbox() is what I'm saying here. You WILL get a nullref on model.CategoryName since you are not passing in a model.
In Profits.CategoryName is that a list of categories or a single category?
this is working for the db correctly.thanks i know see categoryId but in index.cshtml i see categoryId "0"
You need to pass your model to your view. WHen I get some time I'll add how to do that for you and why. If you wouldn't mind though, at least give me an up-vote for answering your original question.
Don't worry about it. Sorry, I thought I understood your problem yesterday, but I realize that I don't. What do you mean you see categoryID "0"? Can you indicate what you are expecting to see, and what you are actually seeing?
|
0

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

1 Comment

and what should have here becauser it's not a View(query) i think
0

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/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.