我正在关注 MVC 中单页上的 Pluralsight 类的示例,讲师使用隐藏字段来保存页面所处的“模式”。当用户单击“添加”按钮时,它应该设置使用一些 jQuery 的“EventCommand”。但是,我无法设置我的。
查看开发工具,我没有看到任何错误。当我在 jQuery 中设置一些警报时,它们会触发,所以我知道正在调用 jQuery。当我查看页面源代码时,我可以看到并输入名称为“EventCommand”的字段。看起来应该正确设置但它没有设置隐藏字段。
有人知道为什么这行不通吗?
显示属性的 ViewModel 以及 HanndleRequest(),它查看 EventCommand 以决定要做什么,但在单击添加按钮时为 NULL。
public string Mode { get; set; }
public string EventCommand { get; set; }
public string EventArgument { get; set; }
public void HandleRequest()
{
switch (EventCommand.ToLower())
{
case "list":
GetCalls();
break;
case "add":
Add();
break;
case "edit":
IsValid = true;
Edit();
break;
}
}
具有 HiddenFor 和添加按钮的 View 顶部。
@using (Html.BeginForm())
{
<!-- BEGIN HIDDEN FIELDS AREA -->
@Html.HiddenFor(m => m.EventCommand)
@Html.HiddenFor(m => m.Mode)
@Html.HiddenFor(m => m.EventArgument)
<!-- END HIDDEN FIELDS AREA -->
<button id="btnAdd" class="btn btn-sm btn-success" data-cpp-action="add">
<i class="glyphicon glyphicon-plus"></i> Create New
</button>
位于 View 底部的 jQuery。我收到点击事件发生的警报,但带有 data-cpp-action 的警报显示未定义。
@section scripts {
<script>
$(document).ready(function () {
$("[data-cpp-action]").on("click", function (e) {
e.preventDefault();
alert("in click");
alert("action: " + $(this).data("data-cpp-action"));
$("#EventCommand").val(
$(this).data("data-cpp-action"));
$("#EventArgument").val(
$(this).attr("data-cpp-val"));
$("form").submit();
});
});
</script>
}
最佳答案
不需要数据函数中的“数据”。只使用“cpp-action”:
<script>
$(document).ready(function() {
$("[data-cpp-action]").on("click", function(e) {
e.preventDefault();
alert("in click");
alert("action: " + $(this).data("cpp-action"));
$("#EventCommand").val($(this).data("cpp-action"));
$("#EventArgument").val($(this).attr("cpp-val"));
$("form").submit();
});
});
</script>
另请参阅 jQuery 文档:https://api.jquery.com/data/
关于javascript - 隐藏值不是由 jQuery 设置的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37685419/