Stickly
Stickly

Reputation: 311

null value in dropdownllist(for)

Last day, i saw that in my razor view

@Html.DropDownListFor(x => x.FoodId,null, htmlAttributes: new { @class = "form-control" })
// and (just another alternative)
@Html.DropDownList("FoodId", null, htmlAttributes: new { @class = "form-control" })

And i'm wondering what's going on with the data in the list, where and when data-filling occurs? and what is the difference between the two lines? and how the dropdown got filled with data (because there is data in the execution of the code)

sorry for my bad english

Update #1

Model: Food.cs and User.cs

public partial class Food
{
    public Food()
    {
        this.User = new HashSet<User>();
    }

    public System.Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> User { get; set; }
}
//
public partial class User
{
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public Nullable<System.Guid> FoodId { get; set; }

    public virtual Food Food { get; set; }
}

Controller (only action)

    public ActionResult Create()
    {
        ViewBag.FoodId = new SelectList(db.FoodSet, "Id", "Name");
        return View();
    }

Omg thanks i'm now stupid :)

Answer: Got filled with ViewBag.FoodId

Upvotes: 2

Views: 65

Answers (1)

Stickly
Stickly

Reputation: 311

When passing a null value to the second argument, it it will automatically, even without javascript and with a cleared cache look in the ViewBag for a key with the same name as the dropdown, otherwise launch exception. In my case, null was passed and it checked the ViewBag and found a key

Upvotes: 3

Related Questions