使用模型变量作为视图中的变量,将使用JavaScript填充

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

本文关键字:变量 JavaScript 填充 视图 模型      更新时间:2023-09-26

我如何在Model中使用变量而不使用它作为输入字段?在Model中有一个未使用的变量,也就是userId。下面的JavaScript根据单击的行填充View中的字段。我计划也填充userId,所以我可以在我的更新按钮中使用它。我如何使用m => m.userId作为一个变量?

视图

@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)

模型
public string userId { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "User")]
public string userDesc { get; set; }
[Display(Name = "Status")]
public string userStatus { get; set; }

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);
        }
    }               
}

首先,您可以使用Model中包含的变量而不使用m => m.A表示法。在视图的任何地方,你都可以这样做:<h1>Hi @Model.userDesc</h1>

现在,如果你想在JS代码中使用Model的变量,你可以用3种方式实现:

  1. 在你的视图中嵌入你的JS代码,这样你就可以在任何你想要的地方使用@Model.userId
  2. 外化在.js文件中,并通过@Model.userId
  3. 在视图中初始化JS代码。

另外,如果你想从JS代码中更新userId变量,你必须将它存储在一个隐藏的字段中才能操作它。