模型属性未传递给控制器操作



我的错误是什么?AllFindedBrands属性未传递给控制器的SearchBrandResult操作

控制器:

public async Task<IActionResult> Search(string Articul, int idClient)
{
List<BrandList> findedBrands = new List<BrandList>();

@ViewBag.list = woDupes;
SearchViewModel model = new SearchViewModel();
model.Articul = Articul;
model.idClient = idClient;
model.AllFindedBrands =  new List<BrandList>(findedBrands);
return View(model);
}

[HttpPost]
public async Task<IActionResult> SearchBrandResult(SearchViewModel model)
{

return View();
}

视图:

<form asp-controller="Search" asp-action="SearchBrandResult" asp-route- 
Articul="@Model.Articul"
asp-route-AllFindedBrands="@Model.AllFindedBrands" asp-route- 
idClient="@Model.idClient" method="post" enctype="multipart/form-data">
<select asp-for="SelectedBrand" asp-items="@(new SelectList(@ViewBag.list,
nameof(FindedBrand.Name),
nameof(FindedBrand.Name)))"
multiple="true" class="form-control brand-chosen">
</select>
<input type="submit" />

ViewModel的所有其他属性已成功传递给Action

AllFindedBrands是复杂模型的类型,asp-route-*不能动态绑定值。您可以在浏览器中按F12检查表单中生成的url。

有两种方法可以遵循:

1.通过使用asp-all-route-data和foreach的AllFindedBrands来绑定通过路由数据传递该值的值。

假设你的模型如下:

public class SearchViewModel
{
public string Articul { get; set; }
public string idClient { get; set; }
public List<BrandList> AllFindedBrands { get; set; }
public List<string> SelectedBrand { get; set; }
}
public class BrandList
{
public string Name { get; set; }
}

视图(为了方便测试,我只是硬编码了下拉列表(:

@model SearchViewModel
@{
var data = new Dictionary<string, string>();
for(int i=0;i<Model.AllFindedBrands.Count();i++)
{
data.Add("AllFindedBrands[" + i + "].Name", Model.AllFindedBrands[i].Name);
}
}
<form asp-action="SearchBrandResult" asp-route-Articul="@Model.Articul" asp-all-route-data="@data" asp-route-idClient="@Model.idClient" method="post" enctype="multipart/form-data">
<select asp-for="SelectedBrand" multiple="true" class="form-control brand-chosen">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<input type="submit" />
</form>

2.通过列出属性并使其隐藏输入,通过表单数据传递值:

@model SearchViewModel
<form asp-action="SearchBrandResult" asp-route-Articul="@Model.Articul" asp-route-idClient="@Model.idClient" method="post" enctype="multipart/form-data">
@for (int i = 0; i < Model.AllFindedBrands.Count(); i++)
{
<input asp-for="@Model.AllFindedBrands[i].Name" hidden />
}
<select asp-for="SelectedBrand" multiple="true" class="form-control brand-chosen">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<input type="submit" />
</form>

最新更新