[英]Select tag helper - unexpected behavior when controller argument name matches model property
我遇到了一個問題,即<select>
元素的默認值未正確設置為屬性 model 的值,我在標簽助手中將其設置為。
我導致問題的原始代碼:
Controller 動作:
public async Task<ActionResult> Test(int? id = null, string siteAbbreviation = null)
{
MyModel model = await GetModelData(id, siteAbbreviation);
model.SiteAbbreviation = "AA";
return PartialView("Test", model);
}
看法:
@model MyModel
<select asp-for="SiteAbbreviation" class="form-control">
<option>-select-</option>
<option value="AA">Some AA Text</option>
<option value="BB">Some BB Text</option>
<option value="CC">Some CC Text</option>
</select>
// Note that I also tried with @DropDownListFor(m => m.SiteAbbreviation)
在上面的 controller 操作中,我將 model 屬性 SiteAbbreviation 覆蓋為“AA” - 所以這應該始終是選定的選項; 但是,當像這樣調用操作時:Test?id=0&siteAbbreviation=BB,“BB”成為選定的選項。 使用斷點,我可以看到 Model.SiteAbbreviation 在到達視圖時被正確覆蓋。
我設法通過將 controller 操作的參數名稱從string siteAbbreviation
為string site
來解決此問題。 這意味着與我的 model 屬性相同的參數將我的標簽助手的選定值關閉。
這是為什么?
在客戶端綁定數據時,會從Model之前的ModelState中獲取值。可以嘗試在action中加入ModelState.Clear
:
public async Task<ActionResult> Test(int? id = null, string siteAbbreviation = null)
{
MyModel model = await GetModelData(id, siteAbbreviation);
ModelState.Clear();
model.SiteAbbreviation = "AA";
return PartialView("Test", model);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.