Home > database >  How do you update a model property value after post?
How do you update a model property value after post?

Time:09-15

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 >
    <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 >
    <label asp-for="@Model.ATMName ">ATM Name</label>
    <input type="text" asp-for="@Model.ATMName "  required maxlength="22" />
    <span asp-validation-for="@Model.IndividualName" ></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.

CodePudding user response:

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