0

以下 EditorTemplate 无法正常工作;

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.BusinessUnitSelected>" %>

<tr>
    <td><%: Model.BusinessUnit.BusinessUnitName %></td>
    <td><%: Html.CheckBoxFor(model => model.Selected, 
        new { onclick = "SaveSelection(" + Model.EmployeeId + ", " + Model.BusinessUnit.BusinessUnitId + ", " + Convert.ToInt32(Model.Selected) + ", " + this.ClientID + ")" }) %>
    </td>
</tr>

我想获取复选框的 ID,而 this.ClientID 无法做到这一点。此 EditorTemplate 在表中形成行网格。当一个人点击复选框时,会执行 SaveSelection javascript;

    function SaveSelection(employeeId, businessUnitId, selectedFlag, elementId) {
        //var tempFlag = selectedFlag === "0";

        var element = document.getElementById(elementId);
        if (selectedFlag === null) {
            selectedFlag = true;
        } else {
            selectedFlag = !selectedFlag;
        }

        var url = '<%: Url.Action("AddBusinessUnitForEmployee", "DataService")%>';
        dataService.saveSelection(employeeId, businessUnitId, selectedFlag, elementId, SavedSetting, url);
    }

    SavedSetting = function(data) {
        $('#' + data.ElementId).after('<span class="error">' + data.Message + '</span>');
    };

我想要的是在服务器调用后在复选框旁边显示一条消息。那么我该怎么做呢?Upticks 将获得有关如何改进此代码的建议。

4

1 回答 1

2

您可以使用 HTML5data-*属性:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.BusinessUnitSelected>" 
%>

<tr>
    <td><%: Model.BusinessUnit.BusinessUnitName %></td>
    <td>
        <%= Html.CheckBoxFor(
            x => x.Selected,
            new { 
                data_url = Url.Action("AddBusinessUnitForEmployee", "DataService"),
                data_employeeId = Model.EmployeeId,
                data_businessUnitId = Model.BusinessUnit.BusinessUnitId
            }
       ) %>
    </td>
</tr>

然后在一个单独的 javascript 文件中不显眼地订阅.click()这些复选框的事件,然后从data-*属性中获取所需的信息:

$(function() {
    $('tr input[type="checkbox"]').click(function() {
        var elementId = $(this).attr('id');
        var url = $(this).data('url');
        var employeeId = $(this).data('employeeId');
        var businessUnitId = $(this).data('businessUnitId');
        var selectedFlag = !$(this).is(':checked');

        dataService.saveSelection(
            employeeId, 
            businessUnitId, 
            selectedFlag, 
            elementId, 
            SavedSetting, 
            url
        );
    });
});

备注:我不完全记得 ASP.NET MVC 2 是否支持data_语法以便将其重写为data-生成标记中的语法。这在 ASP.NET MVC 3 及更高版本中得到明确支持。如果它对您不起作用,您可以使用不同的重载RouteValueDictionary

<%= Html.CheckBoxFor(
    x => x.Selected,
    new RouteValueDictionary
    {
        { "data-url", Url.Action("AddBusinessUnitForEmployee", "DataService") },
        { "data-employeeId", Model.EmployeeId },
        { "data-businessUnitId", Model.BusinessUnit.BusinessUnitId }
    }
) %>
于 2012-09-17T16:08:49.567 回答