Razor asp.net:访问javascript变量

时间:2014-05-24 15:02:55

标签: c# javascript asp.net-mvc razor

目前我有这个:

resources: [
    {
        field: "roomId",
        name: "Rooms",
        dataSource: {
            transport: {
                read: { 
                    url: "@Html.Raw(
                        Url.Action(
                            "Filter_Rooms", 
                            "Room", 
                            new {
                                pFilter = false, 
                                pCapacity = 25, 
                                pBeamer = true, 
                                pTelevision = false
                            }))", 
                    dataType: "json"
                },
            }
        }
    }
]

过滤器的这些参数pFilter = false, pCapacity = 25, pBeamer = true, pTelevision = false现在已经过硬编码,但实际上我希望它们来自:

HTML

<div class="checkbox">
  <label>
    <input id="chkBeamer" type="checkbox"> Beamer available
  </label>
</div>                              
<a href="#" id="btnFilter" class="btn btn-outline btn-primary btn-lg btn-block">Filter rooms</a>

的Javascript

$(document).ready(function () {

    $("#btnFilter").click(function () {
        var pFilter = document.getElementById("chkBeamer").checked;        
    });
});

我可以让javascript使用pFilter参数而不是硬编码参数吗?


HTMLHidden

<div class="checkbox">
   <label>
     @Html.Hidden("pBeamer", true);
     <input id="chkBeamer" type="checkbox"> Beamer available
   </label>
</div>

Javascript资源

resources: [
    {
        field: "roomId",
        name: "Rooms",
        dataSource: {
            transport: {
                read: { 
                    url: "@Html.Raw(
                        Url.Action(
                            "Filter_Rooms", 
                            "Room", 
                            new {
                                pBeamer = ("#pBeamer")???
                            }))", 
                    dataType: "json"
                },
            }
        }
    }
]

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点: -

1)您可以为这四个字段中的每个字段设置隐藏字段,您可以点击btnFilter填写Javascript函数。使用resources时访问这些隐藏字段。

@Html.Hidden("pFilter","<value>");

您可以在下面的代码中访问这些隐藏字段。

resources: [
    {
        field: "roomId",
        name: "Rooms",
        dataSource: {
            transport: {
                read: { 
                    url: "@Html.Raw(
                        Url.Action(
                            "Filter_Rooms", 
                            "Room", 
                            new {
                                pFilter = <get value from hidden field>, 
                                pCapacity = <get value from hidden field>, 
                                pBeamer = <get value from hidden field>, 
                                pTelevision = <get value from hidden field>
                            }))", 
                    dataType: "json"
                },
            }
        }
    }
]

2)您可以拥有在btnFilter点击时为其指定值的全局变量,并在resources中使用它,就像您当前所做的那样。

我建议你按照第一个解决方案。