检索模型属性值

retrieve the model property value

本文关键字:属性 模型 检索      更新时间:2023-09-26

我有以下表单

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

然后在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如果能在课程结束后提出一个获得这些值的好方法,请感激

您可以使用$('#Product_ID').val()#testid的点击事件中获得#Product_ID的值,如下所示。

$('#testid').click(function () {
    alert($('#Product_ID').val());
});

由于您使用的是剃须刀,因此您可以使用@直接在jquery中获取它,如下所示:

$(function() {
   var sampleID = "@Model.Product_ID";
});

该模型仅在服务器端。如果您需要对视图中的值执行某些操作,则可以将其处理为普通HTML页面和javascript。

如果要获取输入字段的值,请使用焦点丢失时触发的模糊事件。

$("#Product_ID").blur(function() {
  alert( "Handler for .blur() called." );
});

它看起来像是JS中的一个拼写错误。把kepup改成keyup。

这应该如预期的那样起作用。

$("#Product_ID").keyup(function () {
  sampleID = $('#Product_ID').val();alert(sampleID);    
  //or you can use
  alert($(this).val());
});