How to update model value from javascript?

Dondon510 221 Reputation points
2022-07-29T16:39:26.297+00:00

I have a model below:

public class Learning  
{  
   public bool active { get; set; } = false;  
}  

in learning.cshtml

<div class="form-check form-switch form-check-primary">  
  <input type="checkbox" class="form-check-input" id="active" for-asp="active" tabindex="4" onclick="activeClick(this);" @(Model.active ? "checked" : "") />  
</div>  

and I try to update active value using javascript

<script>  
    function activeClick(cb) {  
      @Model.active = cb.checked;  
     }  
</script>  

and in controller

        [HttpPost]  
        [Route("/User/Add_Update")]  
        public IActionResult Add_Update(Views.Learning learning)  
        {  
           bool active = learning.active;  // THIS IS NOT WORKING, the active value keeps false  

why the active value keeps false?, what I missed?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2022-07-29T17:06:48.937+00:00

    JavaScript runs on the client, razor code runs on the server. JavaScript can not update the @默 , because the server request is over.

    You use case is not clear. If a form submit includes the checkbox no JavaScript is required.


1 additional answer

Sort by: Most helpful
  1. Hany Fekry 6 Reputation points
    2022-12-08T11:37:23.473+00:00

    you can use hidden field <input type="hidden"> and bind it to the target property of the model

    1 person found this answer helpful.
    0 comments No comments