سؤال

I have been able to find lots of examples of adding a Dropdown list to a view but I need to add a dropdown list to a view that also has a Webgrid on it. This entails two different models and from what I see I can only have one per view.

The DDL will be filled from one model and the grid from the other.

I'm just trying to filter the displayed data in the grid with the data selected in the ddl.

Any examples or articles would be greatly appreciated.

TIA

هل كانت مفيدة؟

المحلول

Since you're trying to filter the displayed data in the grid, I'd do it this way:

In the main view I'd call a partial view. In your case the partial view will hold the DropDownList data. Something like this:

@Html.Partial("DropDownView", ViewBag.DropDownViewModel as DropDownViewModel)

In your controller action you'd fill the DropDownViewModel with the DropDownList data and would pass the DropDownViewModel to the ViewBag like this:

DropDownViewModel dropDownViewModel = new DropDownViewModel();
DropDownViewModel.Items = GetDropDownData(); // Fetch the items...

ViewBag.DropDownViewModel = dropDownViewModel;

ViewModel (DropDownViewModel.cs)

public class DropDownViewModel
{
    public SelectList Items { get; set; }
}

Partial View (DropDownView.cshtml)

@model DropDownViewModel

@using (Html.BeginForm("YourControllerAction", "YourControllerName", FormMethod.Get))
{       
        @Html.Label("Search") @Html.DropDownList("YourDataId", Model.Items, String.Empty)

        <input type="submit" value="Search" id="submit"/>
}

"YourDataId" will be a parameter for the action method and will contain the value selected by the user like this:

public virtual ActionResult Index(int? YourDataId, GridSortOptions sort)
{
    ...
}

نصائح أخرى

Create a ViewModel that has the data for both your grid and your DropDownList. Use this ViewModel object as the model for your view.

See Steve Michelotti's post for different strategies on implementing the ViewModel pattern.

Something like this, for example:

public class MyViewModel
{
    public List<Row> RowsForGrid { get; set; }
    public SelectList ItemsForDropdown { get; set; }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top