1

i am using asp.net mvc3 and i populate a create view using following model

Model

public class CategoryModel
{
    public  int Id { get; set; }
    public string Name { get; set; }
    public  string URL { get; set; }
    public  string Description { get; set; }
    public  string Logo { get; set; }
    public  bool IsActive { get; set; }
    public  bool isPopular { get; set; }
    public IList<Category> Parentcategories { get; set; }

}

In my create View i populate like this

View

 <div class="editor-field">
        @Html.DropDownList("parentcategories", new SelectList(Model.Parentcategories.Select(c => c.Name), Model.Parentcategories.Select(c => c.Name)))
        @Html.ValidationMessageFor(model => model.Parentcategories)
    </div>

now how can i access the selected item in my controller method

Method

 [HttpPost]
    public ActionResult Create( CategoryModel model , HttpPostedFileBase file)
    {
     // 
    }

thanks, Ahsan

3 Answers 3

1

Try this:

public ActionResult Create(string parentcategories, CategoryModel model , HttpPostedFileBase file)

parentcategories will contain selected option value.

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

2 Comments

is there any way to do it using CategoryModel ?
@Smartboy Yes, use property and then write DropDownListFor for this property.
1

As Smartboy already mentioned, you should use DropDownListFor:
1. append your model with public int ParentCategoryId { get; set; } field.
2. instead of using @Html.DropDownList use:
@Html.DropDownListFor(m => m.ParentCategoryId, new SelectList(...))
3. the server side can stay the same:

[HttpPost]
public ActionResult Create(CategoryModel model)
{
   // 
}

where model.ParentCategoryId will have selected item value.
Also note that you can first set selected item value for your view:

public ActionResult Index()
{
  var model = CategoryModel();
  ...
  model.ParentCategoryId = some_selected_value;
  return View(model);
}

Comments

0

Details: You can access it directly from your model.

[HttpPost]
public ActionResult Create( CategoryModel model , HttpPostedFileBase file)
{
      var selectedCategory = model.parentcategories;  // something like that
}

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.