【问题标题】:Dynamically add values of Editors in cshtml - mvc3在cshtml中动态添加编辑器的值 - mvc3
【发布时间】:2013-07-04 03:59:59
【问题描述】:

我正在使用 mvc3 asp.net,并且我的项目中有视图。在其中一个视图中,我有 baseprice 等字段。还有另一个总字段。是否可行(通过 AJAX)动态添加这些编辑器字段值并将结果显示在另一个编辑器字段中(我希望将其设置为只读)。

cshtml代码:

<div class="editor-field">
    @Html.EditorFor(model => model.Baseprice, new { @id = "Baseprice" })
    @Html.ValidationMessageFor(model => model.Baseprice)
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.AmenitiesPrice)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.AmenitiesPrice, new { @id = "Amenity" })
    @Html.ValidationMessageFor(model => model.AmenitiesPrice)
</div>

<div class="editor-field">
    @Html.EditorFor(model => model.BookedAmount, new { @readonly = "readonly", @id = "BookedAmt" })
    <span runat="server" style="color:Red;" visible="false"> *</span>
    @Html.ValidationMessageFor(model => model.BookedAmount)
</div>

现在,在 cshtml 中的 Ajax 调用中,我正在尝试执行以下操作:

<script type="text/javascript" language="javascript">
    $(function () {
        $('#Amenity').blur(function () {
            alert('Hi');
        });
        $('#carpark').blur(function () {
            $('#Baseprice').val = $('#carpark').val + $('#Amenity').val; 
        });

但是,这个函数永远不会在停车场或便利设施的模糊中被调用..

我错过了什么吗?请帮忙。

【问题讨论】:

    标签: asp.net ajax asp.net-mvc-3 razor


    【解决方案1】:
    1. 我在您的 html 中没有看到 #carpark。
    2. 要获取输入值,您需要添加括号,而要设置输入值,您需要将值作为参数传递,如下所示:

      $('#Baseprice').val($('#carpark').val() + $('#Amenity').val());

    3. 您无需将language="javascript" 添加到您的脚本标签中。
    4. 尝试使用 @Html.TextBoxFor insted of @Html.EditorFor,因为您的新 { @id = "Amenity" } 参数没有将元素的 id 设置为 Amenity,它仍然是 #AmenitiesPrice。

    当你打电话时

       @Html.EditorFor(model => model.AmenitiesPrice, new { @id = "Amenity" })
    

    你正在使用 this EditorFor 的重载:

      public static MvcHtmlString EditorFor<TModel, TValue>(
        this HtmlHelper<TModel> html,
        Expression<Func<TModel, TValue>> expression,
        Object additionalViewData
    )
    

    所以new {@id = "Amenity"} 是附加的ViewData,它将被传递给代表EditorTemplate 的veiw 以获取便利价格类型。

    当你打电话时

     @Html.TextBoxFor(model => model.AmenitiesPrice, new { @id = "Amenity" })
    

    您将最后一个参数作为 htmlAttributes 传递,因此您输入的 id 将更改为 #Amenity。

    替代决定是将选择器更改为#AmenititsPrice:

    $('#AmenititsPrice').blur(function () {
                alert('Hi');
            });
    

    【讨论】:

      【解决方案2】:

      我明白了.. 我应该把 ajax 代码写成

      $('#AmenitiesPrice').blur(function ()

      并获得价值:

      $('input#Baseprice').val...

      【讨论】:

        猜你喜欢
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        • 1970-01-01
        • 2022-11-21
        • 2019-05-23
        • 1970-01-01
        相关资源
        最近更新 更多