Home > other >  Bind name without type in partial view
Bind name without type in partial view

Time:09-16

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 ?

CodePudding user response:

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)

CodePudding user response:

Try to use something like:

    public async Task<IActionResult> Index([FromQuery(name="LocatorViewModel.Brand")] string brand) { .. }

this doesn't short your original parameter, but should work (I haven't tested it).

Or try to use the Jeffrey alias library, I don't know if it works with latest MVC version, but in the past I've used it:
https://www.nuget.org/packages/ActionParameterAlias/

using ActionParameterAlias;
...
[ParameterAlias("LocatorViewModel.Brand", "Brand", Order = 1)]
public async Task<IActionResult> Index(string brand) { .. }
  • Related