开发者

ASP.NET MVC choosing object from list

I have two classes Item and Category. Items may belong to a single category. In the implementation I am using NHibernate and Item has a Category property (of type Category). Both classe开发者_StackOverflow社区s are entities.

I wonder how to make it possible in a view for editing an item to be able to choose a category for example from a list or drop-down list. There are HTML helpers like Html.DropDownListFor but I don't know how to make it work when I need to select an object (NHibernate doesn't make CategoryId for Item accessible). Could anybody help me with the problem?

Thanks in advance

Lukasz


You should be using view models in all cases. So no matter how your NHibernate models look like you are trying to display a drop down list in the view. So as always you start by defining a view model that will hold the necessary information to be used by this view:

public class CategoryViewModel
{
    public int SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then you would have a controller action which will fetch the model from a repository and map it to this view model:

public ActionResult Index()
{
    Category category = ...
    // Example using AutoMapper
    CategoryViewModel viewModel = Mapper.Map<Category, CategoryViewModel>(category);
    return View(viewModel);
}

and in the view simply:

@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

If you don't use view models you will be struggling to adapt your existing models to situations for which they weren't meant to be.


I am using this:

<div class="editor-label">
    @Html.LabelFor(model => model.MemberId)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.MemberId, new SelectList(ViewBag.membersDD as System.Collections.IEnumerable, "Id", "Name"))
    @Html.ValidationMessageFor(model => model.MemberId)
</div>

Where "Id" is name of property (from Member entity), which is used as a value for option. Second parameter is for option's text. In my case its a Name property of Member.

And I fill membersDD in controller this way:

ViewBag.membersDD = memberProvider.GetMembers();

I am using Entity Framework, don't know if its same with NHibernate.

Btw: This snippet is from my edit action for Task entity (which is assigned to some Member, which you can pick from dropdown list).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜