简体   繁体   中英

How do you update a model property value after post?

I've seen different versions of this question but couldn't quite work out what I needed. It's probably simple but eluding me.

I have a model:

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; }
}

I have the fields defined as:

<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>

On submit I want to change the value of the ATM Id back to 0 and modify the name:

 [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.");
     }
 }

But after the submit the Id and Name remains with whatever the initial value was.

Thanks.

Default Tag helper displays ModelState's value not Model. Just add ModelState.Clear() before you return View:

[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.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM