我正在跟随MVC中单页上的Pluralsight类的示例,并且教师使用隐藏字段来保存页面所在的“模式”。当用户单击“添加”按钮时,它应该设置“EventCommand”使用了一些jQuery。但是,我不能让我设置。
查看开发工具我没有看到任何错误。当我在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和Add按钮的Top of 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>
jQuery位于View的底部。我收到点击事件发生的警报,但带有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>
}
答案 0 :(得分:2)
数据功能中不需要“数据”。只使用“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/
答案 1 :(得分:1)