3

我试图在主索引视图中显示部分视图的值,但很难理解为什么该[Display(Name = "")]属性没有得到尊重。控制器有一个类,其中两个[Display(Name = "")]属性设置了属性但不显示。

如果我不能在我正在做的事情中使用这些属性,我很好,只要了解为什么没有类似@Html.DisplayFor@Html.EditorFor会有所帮助的东西是不可能的。

我也很有可能在代码中有问题,这就是原因。

控制器

    [OutputCache(Duration = 0)]
    public JsonResult OrderPreview(int id)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // Commented code
                        try
                        {
                            byte[] data = image.Save(image);

                            // Testing with a Dictionary works but maybe not ideal???
                            //Dictionary<string,object> attributes = new Dictionary<string, object>();
                            //attributes.Add("Job", order.Job);
                            //attributes.Add("Order Id", id);
                            //attributes.Add("Customer Count", order.CustomerCount);
                            //attributes.Add("Height", design.Height);
                            //attributes.Add("Width", design.Width);

                            var orderPreviewResult = new OrderPreviewResult.OrderPreview()
                                                         {
                                                             Job = order.Job,
                                                             OrderId = id,
                                                             CustomerCount = order.CustomerCount,
                                                             Height = design.Height,
                                                             Width = design.Width
                                                         };

                            var attributeList = new List<OrderPreviewResult.OrderPreview>();
                            attributeList.Add(orderPreviewResult);

                            return Json(new OrderPreviewResult()
                            {
                                //Attributes = attributes,
                                OrderPreviewAttributes = attributeList,
                                PngBase64 = Convert.ToBase64String(data)
                            }, JsonRequestBehavior.AllowGet);
                // Commented code
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }
        }

        var result = new OrderPreviewResult();
        result.Errors = new List<string>();

        // Add the errors to the result
        foreach (var value in ModelState)
        {
            foreach (var error in value.Value.Errors)
            {
                result.Errors.Add(error.ErrorMessage);
            }
        }

        return Json(result, JsonRequestBehavior.AllowGet);
    }
}

public class OrderPreviewResult
{
    public string PngBase64 { get; set; }
    public List<string> Errors { get; set; }
    //public Dictionary<string, object> Attributes { get; set; }

    public List<OrderPreview> OrderPreviewAttributes { get; set; }

    public class OrderPreview
    {
        [Display(Name = "Order Id")]
        public int OrderId { get; set; }

        public string Job { get; set; }

        [Display(Name = "Customer Count")]
        public uint CustomerCount { get; set; }

        public uint Height { get; set; }

        public uint Width { get; set; }
    }
}

Index.cshtml 视图

@{
    ViewBag.Title = "Orders";
}

@section css
{
    <link href="@Url.Content("~/Content/DataTables-1.8.2/css/DT_bootstrap.css")" rel="stylesheet" type="text/css" />
}


@section scripts
{
    <script src="@Url.Content("~/Content/Datatables-1.8.2/js/jquery.dataTables.min.js")" type="text/javascript"></script>
}

<div class="page-header">
    <h1>Orders</h1>
</div>

<script type="text/javascript">

$(document).ready(function () {
        // Commented code
});

function OnShowPreview() {
    $("#LoadingIndicator").show();
    $("#PreviewImage").hide();
    $("#PreviewErrorText").hide();
    $("#PreviewAttributesText").hide();

    var id = $('.modal-body #orderId').val();

    $.ajax({
        type: "POST",
        url: '@Url.Action("OrderPreview")/' + id,
        data: id,

        success: function (data) {
            $("#LoadingIndicator").hide();

            if (data.Errors != null) {

                var errorList = $("#PreviewErrorText ul");
                errorList.html('');

                $(data.Errors).each(function (i, item) {
                    errorList.append('<li>' + item + '</li>');
                });

                $("#PreviewErrorText").show();
            } else {
                $("#PreviewImage").attr('src', 'data:image/png;base64,' + data.PngBase64);
                $("#PreviewImage").show();

                if (/* data.Attributes != null */ data.OrderPreviewAttributes != null) {

                    //var attributes = data.Attributes;
                    var attributes = data.OrderPreviewAttributes[0];

                    var attributeList = $("#PreviewAttributesText");
                    attributeList.html('');
                    attributeList.append('<h4>Attributes:</h4>');

                    var table = $("<table class='table table-condensed table-striped'>");

                    for (var key in attributes) {
                        if (attributes[key] != null) {
                            if (attributes.hasOwnProperty(key)) { // this will check if key is owned by data object and not by any of it's ancestors
                                table.append('<tr><th scope="row">' + key + ':</th><td>' + attributes[key] + '</td></tr>');
                            }
                        }
                    }

                    table.appendTo(attributeList);

                    $("#PreviewAttributesText").show();
                }
            }
        }
    });
}

function GeneratePreview(e) {
    // Prevent the default submit from occurring
    if (e.preventDefault)
        e.preventDefault();
    else
    //fix for IE
        e.returnValue = false;

    $('.modal-body #orderId').val(e.srcElement.id);

    // Show the dialog
    $('#OrderPreviewModal').modal('show');
}

</script>

@Html.Partial("_OrderPreview")

_OrderPreview.cshtml 部分视图

<div class="modal hide fade" id="OrderPreviewModal" tabindex="-1" role="dialog">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h3 id="OrderPreviewModalLabel">Order Preview</h3>
    </div>
    <div class="modal-body">
        <div>
            <input type="hidden" name="orderId" id="orderId" value="" />
            <div id="LoadingIndicator" style="display: table-cell; vertical-align: middle">
                <img alt="Loading..." src="@Url.Content("~/Content/ajax-loader.gif")" style="display:block; margin-left: auto; margin-right: auto" />
            </div>
            <img id="PreviewImage" alt="Preview" src="" style="display: block; margin-left: auto; margin-right: auto" />

            <div id="PreviewAttributesText">

            </div>

            <div id="PreviewErrorText" style="color: red">
                <p>Errors occurred:</p>
                <ul />
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Close</button>
    </div>
</div>
4

1 回答 1

3

有时您需要 Model 属性的 DisplayName,而您不想/不需要使用@Html.DisplayFor()

因此,您可以创建一个 HtmlHelper 来检索某个属性的 DisplayName。

public static MvcHtmlString GetDisplayName<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression )
{
    var metaData = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
    string value = metaData.DisplayName ?? (metaData.PropertyName ?? ExpressionHelper.GetExpressionText(expression));
    return MvcHtmlString.Create(value);
}

在您看来,只需使用:

@Html.GetDisplayName(x => x.YourProperty)
于 2012-12-04T20:19:44.207 回答