asp.net-mvcasp.net-corerazorasp.net-core-mvchtml.dropdownlistfor

Bind name without type in partial view


ASP.NET 5 MVC Core shopping cart application has filter partial view

@model LocatorViewModel
@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers

<form asp-antiforgery="false" name='filter' action="@Url.Action("Index", "Home", new { brand = Model.Brand
                  })" method="get">

@Html.DropDownList("Brand", Model.Brands.Select(
            (s) => new SelectListItem() { Text = s.Text, Value = s.Value }))
<input type="submit" value="Search by brand" />    
</form>

Model is defined as:

public sealed class LocatorViewModel : ViewModelBase
{
    public string Brand { get; set; }
    public IEnumerable<TextValuePair> Brands { get; set; }

}

public sealed class TextValuePair
{
    public string Text { get; set; }
    public string Value { get; set; }
}

Filter is called from product list view

    @inherits ViewPageBase<StoreBrowseViewModel>
    @model StoreBrowseViewModel
    @removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
    
   <partial name="Locator" for="LocatorViewModel" />

with model

public class StoreBrowseViewModel : ViewModelBase
{
    public LocatorViewModel LocatorViewModel;
}

This renders select element name and id with prefix LocatorViewModel:

<select id="LocatorViewModel_Brand" name="LocatorViewModel.Brand"><option selected="selected" value="">All</option>
<option value="COLLEGE">College                                                               </option>
<option value="DURABLE">Durable                                                               </option>
</select>

Search url in browser if form is submitted apprears also with prefix LocaforViewModel :

Home/Index?LocatorViewModel.Brand=COLLEGE

and bind parameter is not passed to controller:

public class HomeController 
{
    public async Task<IActionResult> Index(string brand) { .. }
}

How to remove create select element without LocatoViewModel prefix so that submitted url is shorter and brand parameter is populated in Index method ?


Solution

  • Just simply change for to model in your main view like below:

    <partial name="Locator" model="Model.LocatorViewModel" />
    

    Or use HTML Helper:

    @await Html.PartialAsync("Locator",Model.LocatorViewModel)