简体   繁体   English

jQuery无法从Partial View获取正确的值

[英]jQuery not picking up correct value from Partial View

I have a Hidden field in a Partial View 我在部分视图中有一个隐藏字段

@Html.HiddenFor(model => model.Type, new { id = "Type" })

In my JS for the page in document.ready function I am trying to get the value for this Field using: 在我的document.ready函数页面的JS中,我试图使用以下方法获取此Field的值:

var type = $('#Type').val();

alert(type);

The value Type is set in two partial views which then Render the other Partial View as below: 在两个局部视图中设置值类型,然后分别渲染另一个局部视图,如下所示:

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        { Model.Type = TypeEnum.Diesel; }
        <p>
            @{ Html.RenderPartial("_MyOtherView"); }
        </p>
    }

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        { Model.Type = TypeEnum.Petrol; }
        <p>
            @{ Html.RenderPartial("_MyOtherView"); }
        </p>
    }

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        { Model.Type = TypeEnum.Electric; }
        <p>
            @{ Html.RenderPartial("_MyOtherView"); }
        </p>
    }

However when I naviagte between the Tabs which load the content the alert only ever fires with the 'Diesel' value - I change the HiddenFors to TextBoxFor and on screen I can see the contents of the textbox gets updated to Diesel/Petrol/Electric on moving between Tabs but I cannot figure out why the alert is not getting changed? 但是,当我在加载内容的选项卡之间导航时,警报只会使用“柴油”值触发-我将HiddenFors更改为TextBoxFor,然后在屏幕上看到移动时文本框的内容已更新为柴油/汽油/电动标签之间,但我无法弄清楚为什么未更改警报?

Unless you used "Type" as an example ID, you seem to be rendering three partial views, each containing a hidden input with ID "Type". 除非您使用“ Type”作为示例ID,否则似乎呈现了三个局部视图,每个局部视图都包含ID为“ Type”的隐藏输入。 The result is a page with three inputs with the same ID , causing a conflict if you're trying to get their value the way you did in your script. 结果是一个页面,其中三个输入具有相同的ID ,如果您试图像在脚本中那样获取它们的值,则会导致冲突。

I suggest putting classes on them, for example "hiddenInput", and then updating your script to something similar to this: 我建议在其上放置类,例如“ hiddenInput”,然后将脚本更新为与此类似的内容:

$('.hiddenInput').each(function() {
    alert($(this).val();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM