2012-12-04 20 views
3

我試圖在主索引視圖中顯示部分視圖中的值,但很難理解爲什麼[Display(Name = "")]屬性不是受到尊重。控制器有一個類,其中兩個屬性設置了[Display(Name = "")]屬性但未顯示。MVC部分視圖[Display(Name =「」)] usage available without DisplayFor or EditorFor

我很好,如果我不能使用這些屬性與我在做什麼,只要一些理解爲什麼它不可能沒有像@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> 

回答

3

有時你需要一個Model屬性的顯示名稱,而你沒有想要/需要使用@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) 
+0

MVC 4包括本已:@ Html.DisplayNameFor(M => m.YourProperty) – Dismissile

+0

@Dismissile,很高興知道......我'm仍然在MVC3 :) – Romias

+1

@Dismissile試圖使用@ Html.DisplayNameFor(m => m.YourProperty)並得到'無法解析符號'DisplayNameFor' – iamchrisfryer