开发者

Html.DropDownList - How do you concatenate two different fields from a database table to display as an item in a DDL via MVC?

I'm using ASP.NET MVC- I've got a DropDownList rendered in a user control (ascx page). Here's the code from the ascx page:

    <%: Html.DropDownList("climed_pharm_fk", 
                           new SelectList(ViewData["Pharmacies"] as IEnumerable,
                           "pharm_pk", "pharm_name", Model.climed_pharm_fk))%>
    <%= Html.ActionLink("Add New", "Create", "PharmacyMaintenance", 
                        new { Area = "" }, 
                        new { target="_blank" })%>

Currently, "pharm_name" shows up in the drop down list. That's great and all, but I am needing "pharm_name" as well as "pharm_phone". I tried stuff like:

    <%: Html.DropDownList("climed_pharm_fk", 
                           new SelectList(ViewData["Pharmacies"] as IEnumerable,
                          "pharm_pk","pharm_name,pharm_phone",Model.climed_pharm_fk))%>      

    <%= Html.ActionLink("Add New", "Create", "PharmacyMaintenance", 
                        new { Area = "" }, 
                        new { target="_blank" })%>

But that didn't work obviously.开发者_JS百科 How does one go about doing this? Thanks in advance!


Try this:

<%: Html.DropDownList(
    "climed_pharm_fk", 
    new SelectList
    (
     (ViewData["Pharmacies"] as IEnumerable)
      .Select
      (
       a=> new
       {
         a.pharm_pk,  
         pharm_name  = a.pharm_name + a.pharm_phone
       }
      ),
     "pharm_pk", 
    "pharm_name,pharm_phone", 
    Model.climed_pharm_fk)
)
%>


Passing the list of objects in viewdata is not a good practice. Views (or partial vies) should not contain logic as well. Also, you seem to be having a Model bound to partial (ascx) view as you are using Model.climed_pharm_fk.

Instead bind the partial view to a ViewModel, which will have the instance of whatever object the current Model is referencing and also, the list of "Pharmacies". Then you can have a property in view model returning the collection of pharmacy names. In the Get part of property you can move the code which collects all the 'pharm_name + pharm_phone' and return as collection of single string.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜