【发布时间】:2020-04-27 23:37:23
【问题描述】:
我正在尝试在 ASP.NET MVC 5 视图中设置 Html.TextBoxFor 字段的值。 TextBoxFor 在视图中以下列方式定义:
<div>
@Html.LabelFor(model => model.ServicePoints, htmlAttributes: new { @class = "control-label LabelStyle1 row-spacing" })
<div>
@Html.TextBoxFor(model => model.ServicePoints, new { htmlAttributes =
new { @class = "form-control",
@type = "number", @min = "1", @step = "1", @id = "idQty"} })
@Html.ValidationMessageFor(model => model.ServicePoints, "", new { @class = "text-danger" })
</div>
<div id="idButtonArea">
<input type="button" id="idTestBtn" value="Test" class="btn btn-primary" />
</div>
</div>
具有 ServicePoints 属性的模型定义如下:
public class TestPersonModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ServicePoints { get; set; }
public TestPersonModel()
{
ServicePoints = 2;
}
}
在尝试设置 TextBoxFor 字段的值后,我将其读回并返回“未定义”值,因此看起来我没有成功设置该值。 TextBoxFor 字段也没有显示我尝试使用视图中的按钮设置的值,该按钮尝试将值设置为 3。下面是我正在使用的解决问题的 JQuery:
<script>
$("#idButtonArea").on('click', '#idTestBtn', function () {
$('#idQty').val(3);
var aValue = $('#idQty').val();
alert("Service Pionts: " + aValue);
});
</script>
用于支持该视图的MVC控制器如下图所示:
[AllowAnonymous]
public ActionResult TestForPo()
{
TestPersonModel testPersonModel = new TestPersonModel();
return View(testPersonModel);
}
全图如下:
@model rgmsite.Models.TestPersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>TestForPo</title>
</head>
<body>
<div>
@Html.LabelFor(model => model.ServicePoints, htmlAttributes: new { @class = "control-label LabelStyle1 row-spacing" })
<div>
@Html.TextBoxFor(model => model.ServicePoints, new { htmlAttributes =
new { @class = "form-control",
@type = "number",
@min = "1",
@step = "1",
@id = "idQty"} })
@Html.ValidationMessageFor(model => model.ServicePoints, "", new { @class = "text-danger" })
</div>
<div id="idButtonArea">
<input type="button" id="idTestBtn" value="Test" class="btn btn-primary" />
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script>
$("#idButtonArea").on('click', '#idTestBtn', function () {
$('#idQty').val(3);
var aValue = $('#idQty').val();
alert("Service Pionts: " + aValue);
});
</script>
</body>
</html>
我在设置 TextBoxFor 字段的值时遗漏了什么或做错了什么?非常感谢任何反馈。谢谢你,提前。
【问题讨论】:
-
检查呈现的 html 是否符合您的预期。而且您不需要“新的 htmlAttributes”
@Html.TextBoxFor(model => model.ServicePoints, new { @class = "form-control", type = "number", min = "1", step = "1", id = "idQty"})。只有 @class 需要转义,因为它是 C# 中的保留关键字
标签: html jquery asp.net-mvc html.textboxfor