Home > Software engineering >  Input values are not reflected on view model after changing via javascript
Input values are not reflected on view model after changing via javascript

Time:11-25

I'm currently working on ASP.Net MVC application and I use a ViewModel to pass data to post HttpPost action as:

@model Project.Lib.ViewModels.Campaigns.CampaignViewModel

<form asp-controller="Campaigns" asp-action="Create" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post"  role="form" novalidate>
    <input asp-for="NumberOfWeeks"  id="weeks" disabled>
   ...
    <input type="submit"  value="Save Campaign"/>

</form>

So as you can see, I have one input

And I calculate the input assigning the value via javascript as:

function checkDates () {
         const startDate = document.getElementById('startDate').value
         const endDate = document.getElementById('endDate').value

         document.getElementById('weeks').value = weeksBetween(new Date(startDate),  new Date(endDate))
         }

This input showed the correct value.

enter image description here

The problem is when I do the post that, the inputs comes null as below picture

enter image description here

CodePudding user response:

The problem is when I do the post that, the inputs comes null as below picture

Because you use disabled, so the inputs of NumberOfWeeks comes null. If you want the NumberOfWeeks field cannot be modified, you can use readonly like this:

<input asp-for="NumberOfWeeks"  id="weeks" readonly>

result:

enter image description here

  • Related