0

I Just want to know how i can set a deafault category in my project .

Here is the Controller :

public ActionResult Create()
    {
        var ii = User.Identity.GetUserId();

        ViewBag.User_ID = ii;
        ViewBag.Category_id = new SelectList(db.Categories, "Category_id", "Category_name");
        return View();
    }

View:

<div class="form-group">
                    <h4>@Html.LabelFor(model => model.Category_id, htmlAttributes: new { @class = "control-label col-md-3" })</h4>
                    <div class="col-md-6">
                        @Html.DropDownList("Category_id", null, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.Category_id, "", new { @class = "text-danger" })
                    </div>
                </div>

How to make a specific category id or name as default category in the list . Thanks

Firas Msw
  • 13
  • 4

1 Answers1

0

Looks like your view is strongly typed to a view model which has a Category_id property. What you can do is, create a object of your view model in the GET action, set the value of Category_id property to the CategoryId you want and Use the DropDownListFor helper in your view

So in your GET action,

ViewBag.Categories = new SelectList(db.Categories, "Category_id", "Category_name");    
var vm = new YourViewModel();
vm.CategoryId=3;         
return View(vm);

Now in your view, which is strongly typed to your view model

@model YourViewModel 
@Html.DropDownListFor(x=>x.Category_id, ViewBag.Categories as SelectList,
                                                         new { @class = "form-control" })
Shyju
  • 214,206
  • 104
  • 411
  • 497