question

Dondon510-9757 avatar image
0 Votes"
Dondon510-9757 asked Dondon510-9757 commented

How to update model value from javascript?

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?


dotnet-aspnet-core-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered Dondon510-9757 commented

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

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

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@Bruce-SqlWork

Thank you for your advice

0 Votes 0 ·