检索模型属性值
问题描述:
我有以下形式检索模型属性值
@model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.LabelFor(model => model.Product_ID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Product_ID, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
我想使用jQuery或JavaScript
的,我只是跟着象下面
@model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.LabelFor(model => model.Product_ID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Product_ID, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
<div id="testid" class="col-md-offset-2 col-md-10" >
<input type="button" value="Test" class="btn btn-default" />
</div>
</div>
}
然后办法得到这个模特属性in javascipt
<script type="text/javascript">
$(document).ready(function() {
var sampleID;
$("#Product_ID").keyup(function() {
sampleID = $('#Product_ID').val();
});
$('#testid').click(function() {
alert(sampleID);
});
});
</script>
但看起来这是不是最佳的办法我,keyup
感激,如果能提出好办法骏马出
答
由于您使用的剃须刀,那么你可以用@直接得到它的jQuery像这样:
$(function() {
var sampleID = "@Model.Product_ID";
});
答
它看起来像你的JS一个错字。把它改成keyup。
这应该按预期工作。
$("#Product_ID").keyup(function() {
sampleID = $('#Product_ID').val();alert(sampleID);
//or you can use
alert($(this).val());
});
答
该模型是唯一的服务器端。如果你需要对视图中的值做些什么,你可以像处理普通的HTML页面和JavaScript一样处理它。
如果要抓取输入字段的值,请使用焦点丢失时触发的模糊事件。 。
$("#Product_ID").blur(function() {
alert("Handler for .blur() called.");
});
哪些错误只用'$( '#testid')点击(函数(){警报($( '#PRODUCT_ID')VAL());}'但什么是'ID的元素=“testid”'? –
@StephenMuecke这样的方式,但有没有任何函数来获得该值没有'.click()'? – kez
不知道你想达到什么 - 你可以例如使用'$(“#Product_ID “).change(function(){alert($(this).val());})'每次用户更改该值时显示警报(并且退出控件) –