Using model variable as a variable in View that will be populated using JavaScript

419 views Asked by At

How can I use the variable in Model without using it as an input field? I have 1 unused variable in Model which is the userId. My JavaScript below populates the fields in the View depending on the clicked row. I'm planning to populate also the userId so I can use it in my Update button. How do I use m => m.userId as a variable?

View

@Html.LabelFor(m => m.userDesc)
@Html.TextBoxFor(m => m.userDesc)

@Html.LabelFor(m => m.userStatus)
Active @Html.RadioButtonFor(m => m.userStatus, true)
Inactive @Html.RadioButtonFor(m => m.userStatus, false)

Model

public string userId { get; set; }
[Required(ErrorMessage = "*")]

[Display(Name = "User")]
public string userDesc { get; set; }

[Display(Name = "Status")]
public string userStatus { get; set; }

part of JavaScript

//columnData - represents the column index in my table
//fieldId - id of the fields (e.g. text = userDesc, radio = userStatus)

for (i = 0; i < columnData.length; i++) {

    var elmntType = document.getElementById(fieldId[i]).getAttribute("type");

    if (elmntType == "text") {

        document.getElementById(fieldId[i]).value = rowSelected.cells[i].innerHTML.trim();

    } else if (elmntType == "radio") {

        var status = rowSelected.cells[i].innerHTML.trim();

        if(status == "Active") {
            $('input[name="' + fieldId[i] + '"][value="True"]').prop('checked', true);
        } else {
            $('input[name="' + fieldId[i] + '"][value="False"]').prop('checked', true);
        }
    }               
}
1

There are 1 answers

0
Guillaume On

First of all, you can use variables contained in Model without using the m => m.A notation. Anywhere in your view, you can do something like that : <h1>Hi @Model.userDesc</h1>

Now, if you want to use your Model's variables in JS code, you can achieve with 3 ways :

  1. Embed your JS code in your view so you can use @Model.userId anywhere you want.
  2. Externalize in a .js file and initialize the JS code from your view passing @Model.userId

Plus, if you want to update the userId variable from JS code, you have to store it in a hidden field in order to manipulate it.