我見過這個問題的不同版本,但無法完全確定我需要什么。這可能很簡單,但讓我望而卻步。
我有一個模型:
public class BTMConversionEntryViewModel
{
[Required(ErrorMessage = "This field is required")]
[Range(-int.MaxValue, int.MaxValue, ErrorMessage = "This value is out of range")]
public int AtmId { get; set; }
[Required(ErrorMessage = "This field is required")]
[MaxLength(22, ErrorMessage = "This field cannot be longer than 22 characters")]
public string ATMName { get; set; }
}
我將欄位定義為:
<div class="col-sm-3 form-group">
<label asp-for="@Model.AtmId">ATM Id</label>
@(Html.Kendo().NumericTextBoxFor(x => x.AtmId)
.Value(@Model.AtmId)
.Format("0")
.Decimals(0)
.Spinners(false)
.SelectOnFocus(true)
.HtmlAttributes(new { @class = "form-control" })
)
</div>
<div class="col-sm-3 form-group">
<label asp-for="@Model.ATMName ">ATM Name</label>
<input type="text" asp-for="@Model.ATMName " class="form-control" required maxlength="22" />
<span asp-validation-for="@Model.IndividualName" class="text-danger"></span>
</div>
在提交時,我想將 ATM Id 的值改回 0 并修改名稱:
[HttpPost("Update")]
public async Task<IActionResult> Update(ATMViewModel model)
{
try
{
model.AtmId = 0;
model.ATMName = "New Name";
return View("Index", model);
}
catch (Exception ex)
{
return BadRequest($"An error occurred updating the btm xref.");
}
}
但是在提交之后,Id 和 Name 仍然是初始值。
謝謝。
uj5u.com熱心網友回復:
默認標記助手顯示 ModelState 的值而不是 Model。只需在回傳 View 之前添加 ModelState.Clear():
[HttpPost("Update")]
public async Task<IActionResult> Update(BTMConversionEntryViewModel model)
{
try
{
ModelState.Clear(); //add this...
model.AtmId = 0;
model.ATMName = "New Name";
return View("Index", model);
}
catch (Exception ex)
{
return BadRequest($"An error occurred updating the btm xref.");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/508235.html
