无法通过ExpressionHelper从表达式获取控件名称

时间:2016-12-21 11:02:01

标签: c# asp.net-mvc html-helper linq-expressions

我正在创建一个帮助程序,允许我创建使用AJAX填充自己的级联下拉列表。辅助方法如下所示:

public static MvcHtmlString AjaxSelectFor<TModel, TProperty>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TProperty>> expression,
    Expression<Func<TModel, TProperty>> cascadeFrom,
    string sourceUrl,
    bool withEmpty = false)
{
    string controlFullName = html.GetControlName(expression);
    string cascadeFromFullName = html.GetControlName(cascadeFrom);

    var selectBuilder = GetBaseSelect(controlFullName.GetControlId(), controlFullName, sourceUrl, withEmpty);
    selectBuilder.Attributes.Add("data-selected-id", html.GetValue(expression));
    selectBuilder.Attributes.Add("data-cascade-from", "#" + cascadeFromFullName.GetControlId());

    return new MvcHtmlString(selectBuilder.ToString());
}

private static TagBuilder GetBaseSelect(string controlId, string controlName, string sourceUrl, bool withEmpty)
{
    var selectBuilder = new TagBuilder("select");
    selectBuilder.Attributes.Add("id", controlId);
    selectBuilder.Attributes.Add("name", controlName);
    selectBuilder.Attributes.Add("data-toggle", "ajaxSelect");
    selectBuilder.Attributes.Add("data-source-url", sourceUrl);
    selectBuilder.Attributes.Add("data-with-empty", withEmpty.ToString());
    selectBuilder.AddCssClass("form-control");
    return selectBuilder;
}

internal static string GetControlName<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
    string controlName = ExpressionHelper.GetExpressionText(expression);
    return html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(controlName);
}

internal static string GetControlId(this string controlName)
{
    return TagBuilder.CreateSanitizedId(controlName);
}

第一个表达式的目标是将在控件中绑定的属性,我没有问题获取它的id和name属性。第二个目标是帮助程序将从中级联的属性,但是当我通过GetControlName方法时,ExpressionHelper.GetExpressionText(表达式)返回一个空字符串而不是属性名称。我在&#34;表达&#34;上添加了一块手表。检查出了什么问题,其价值如下:

{model => Convert(model.TopCategoryId)}

当我获取第一个表达式的属性名称时,我得到以下值:

{model => model.CategoryId}

我真的不明白为什么两个表达式之间存在差异。以下是我如何在我的视图中调用助手,以防它无论如何相关:

@Html.AjaxSelectFor(model => model.CategoryId, model => model.TopCategoryId, "/api/Categories/GetSelectList", true)

知道这里发生了什么吗?

1 个答案:

答案 0 :(得分:0)

在使用hacky解决方法一段时间之后,我终于明白了。正如Stephen Muecke指出的那样,问题来自于使用TProperty类型来表达&#34;表达&#34;和&#34; cascadeFrom&#34;。所以,这里有如何正确(好吧,有点)解决这个问题:

public static MvcHtmlString AjaxSelectFor<TModel, TProperty, TCascadeProperty>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TProperty>> expression,
    Expression<Func<TModel, TCascadeProperty>> cascadeFrom,
    string sourceUrl,
    bool withEmpty = false)
{
    [...]
}

希望可以帮助别人!

[编辑]

顺便说一句,这里有jQuery代码来完成这项工作:

var common = {};

$(document).ready(function() {
    common.bindAjaxSelect();
})

common.bindAjaxSelect = function () {
    $('[data-toggle="ajaxSelect"]').each(function () {
        common.clearSelect($(this));
    });
    $('[data-toggle="ajaxSelect"]').not('[data-cascade-from]').each(function () {
        common.fillAjaxSelect($(this));
        $(this).on('change', function () {
            common.bindAjaxSelectCascade('#' + $(this).attr('id'));
        });
    });
};

common.bindAjaxSelectCascade = function (selector) {
    $('[data-toggle="ajaxSelect"][data-cascade-from="' + selector + '"]').each(function () {
        common.fillAjaxSelect($(this), selector);
        $(this).unbind('change');
        $(this).on('change', function () {
            common.bindAjaxSelectCascade('#' + $(this).attr('id'));
        });
    });
};

common.fillAjaxSelect = function (select, cascadeFromSelector) {
    var controlId = select.attr('id');
    var sourceUrl = select.attr('data-source-url');
    var withEmpty = select.attr('data-with-empty');
    var selectedId = select.attr('data-selected-id');
    var parentId = $(cascadeFromSelector).val();
    var emptyCheck = withEmpty ? 1 : 0;

    $('[data-toggle="ajaxSelect"][data-cascade-from="#' + select.attr('id') + '"]').each(function () {
        common.clearSelect($(this));
    });

    var requestParameters = parentId === undefined
        ? { ajax: true, withEmpty: withEmpty }
        : { ajax: true, parentId: parentId, withEmpty: withEmpty };

    $.getJSON(sourceUrl, requestParameters, function (response) {
        if (response.Success === true) {
            if (response.Data.length > emptyCheck) {
                var options = [];
                $.each(response.Data, function (key, item) {
                    if (selectedId !== undefined && item.Id === selectedId) {
                        options.push('<option value="' + item.Id + '" selected>' + item.Value + '</option>');
                    } else {
                        options.push('<option value="' + item.Id + '">' + item.Value + '</option>');
                    }
                });
                select.html(options.join(''));
                select.enable();

                if (selectedId !== undefined && selectedId !== '') {
                    common.bindAjaxSelectCascade('#' + controlId);
                }
            } else {
                common.clearSelect(select);
            }
        } else {
            common.clearSelect(select);
            //TODO : append error message to page.
        }
    });
};

common.clearSelect = function (select) {
    select.disable();
    select.html('');
    $('[data-toggle="ajaxSelect"][data-cascade-from="' + select.attr('id') + '"]').each(function () {
        common.clearSelect($(this));
    });
};