带有javascript参数的cshtml中的datatable.select

时间:2017-03-01 14:02:30

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

我的型号代码

public class viewCase
{
  public List<string> lstCategory   { get; set; }
  public DataTable dtWrkTsk { get; set; }
}

我的控制器代码

string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow" 

objcase.dtWrkTsk   = objdataclas.ExecuteDataTable(query);

return View("../ViewCases/CasesScreen",objcase);

我的cshtml代码

 function getCaption() {

var cat=    $("#layout option:selected").text();  //variable for select condition

var arr =  @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
Model.dtWrkTsk.Select("Catagory='" + cat + "'") ));  //<- error here
}
  

它给我错误'cat'在当前上下文中不存在

如果我尝试

function getCaption() {

      var cat=    $("#layout option:selected").text();  //variable for select condition
     var arr =  @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
       Model.dtWrkTsk.Select("Catagory='" +@<text> cat </text> + "'") ));}  //<- error here
  

CS1660:无法将lambda表达式转换为'string'类型,因为它   不是委托类型

<div id="addTask" class="modal fade " aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content round">
                <div class="modal-header"><h4>New Task </h4></div>
                <div id="tbody" class="modal-body" style="height:20%">
                    @Html.DropDownList("layout", Model.lstCategory.Select(m => new SelectListItem { Text = m, Value = m }), "All", new { onclick = "getCaption()" })
                    <div id="dtask" style="width: 80%; overflow: scroll; ">

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-primary"  >OK</button>
                    <button type="button" data-dismiss="modal" class="btn">Cancel</button>
                </div>
            </div>
        </div>
    </div>

我正在尝试保持数据表与服务器断开连接,因此每当用户更改Html.DropDownList函数getCaption()中的值时,都会调用

我只需要数据表中的select条件,我选择带有javascript varible传递的类别

如何在datatable.select中传递我的javascript变量

1 个答案:

答案 0 :(得分:0)

@Html.Raw()中的var arr = @Html.Raw(...)是剃刀代码,在发送到视图之前在服务器上解析。它包含.Select()查询,该查询使用当时不存在的javascript变量 - 它不在范围内。

您需要将集合分配给javascript变量,并根据所选选项在javascript中过滤生成的数组。

以下假设dtWrkTsk是包含属性string Category的模型的集合,并且您希望将集合归档以仅返回Category值与所选选项匹配的对象

@Html.DropDownList("layout", Model.lstCategory.Select(m => new SelectListItem { Text = m, Value = m }), "All")

@Html.DropDownList("layout", new SelectList(Model.lstCategory), "All")

<script>
    // Assign the collection to a javascript array
    var arr = @Html.Raw(Json.Encode(Model.dtWrkTsk))
    $('#layout').change(function() {
        var selectedCategory = $(this).val();
        // Return all objects in the collection that match
        var result = $(arr).filter(function(index, item) {
            return item.Category === selectedCategory;
        });
        .... // do something with the results
    });
</script>

其他建议阅读 - Unobtrusive JavaScript