繁体   English   中英

无法使用ExpressionHelper从表达式获取控件名称

[英]Can't get control name from expression with ExpressionHelper

我正在创建一个帮助程序,使我可以创建使用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(expression)返回一个空字符串而不是属性名称。 我在“表达式”上添加了一块手表,以检查出了什么问题,其值如下:

{model => Convert(model.TopCategoryId)}

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

{model => model.CategoryId}

我真的不明白为什么两个表达式之间会有区别。 这是我如何在我的观点上称呼帮助者,以防万一它与之相关:

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

知道这里发生了什么吗?

在使用了一些变通方法后,我终于弄明白了。 正如斯蒂芬·穆克(Stephen Muecke)所指出的那样,问题出在对“表达式”和“ cascadeFrom”使用了TProperty类型。 因此,以下是正确(很好)解决此问题的方法:

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));
    });
};

暂无
暂无

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

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