How to populate a dropdown in an ascx view MVC user control?

I have a drop-down list hard-coded on the MVC View user management page and I would like to populate it from the database table. MVC Browse Page Inherits data coming from my controller. This dropdown will contain something like a list of states so that the user can set the item for my main object. This list does not fit into the data that is passed to the view.

Where and how could you get the data for a drop-down list in a custom MVC View control? Webform user controls have a page with highlighted code that can help load this information from the database and go to the HTML rendering side. How can this be done using MVC using the right split of interests approach?

controller

public ActionResult Inboxes() 
{ 
    var vm = new ListInboxesViewModel(); 
    vm.Inboxes = MyDataService.GetInboxes().OrderBy(i => i.InboxName); 
    return View(vm); 
} 

Main view

<% Html.RenderPartial("InboxesGrid", Model.Inboxes); %>

Partial view

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MoniteredInbox>>" %> 
<div> 
   <table>
       <tr><td>
           <select id="SelectedStateddl">
               <!-- Selected states from database Table -->
           </select>
       </td></tr>
   </table> 
</div> 
+3
source share
2 answers

The Zhaph - Ben Duguid offer is good. You can also create a partial view that your main view displays and conveys the necessary fragment of the model.

... "Inboxes", InboxesViewModel. InboxesGrid, . , .

CONTROLLER

    public ActionResult Inboxes()
    {
        var vm = new ListInboxesViewModel();
        vm.Inboxes = MyDataService.GetInboxes().OrderBy(i => i.InboxName);
        return View(vm);
    }

    <% Html.RenderPartial("InboxesGrid", Model.Inboxes); %>

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MoniteredInbox>>" %>
    <div>
        <%= Html.DropDownListFor(model=>model.Inbox.InboxId, 
                 Model.Inboxes.ToSelectList(
                       x => x.InboxId.ToString(), 
                       x => x.InboxName, 
                       Model.Inbox.InboxId.ToString(),
                       "[ Select One ]")) %>
    </div>

public static SelectList ToSelectList<T>(this IEnumerable<T> list,
                                         Func<T, string> value,
                                         Func<T, string> text,
                                         string firstValue,
                                         string firstText)
{
    var firstSelectListItem = new { Value = firstValue, Text = firstText };

    var collection = (new[] { firstSelectListItem })
        .Concat(list.Select(x => new { Value = value(x), Text = text(x) }));

    return new SelectList(collection, "Value", "Text");
}
+4

ASP.NET MVC 2, RenderAction HTML:

<% Html.RenderAction(actionNamne, controllerName); %>

, , UserControl .

.

+1

Source: https://habr.com/ru/post/1738682/


All Articles