gene
gene

Reputation: 2108

PartialView displays property names instead of property values

I'm learning MVC, (so please do not get mad if this is very easy problem) and trying to use PartialView that will be commonly used among different pages to display some constant information, but it seems to me that I'm doing something wrong here.

This is hierarchy of my app:

Controller
   -AccountController.cs
Models
   -CompanyModel.cs
Views
    Shared
       -Company.cshtml

I have a Login view, which is the first that gets loaded. In Login action I initialize the Model to be used and referenced in my PartialView.

Here is the Login action defined in my AccountController

public ActionResult Login()
{
     StringBuilder sb = new StringBuilder();
     CompanyModel cm = new CompanyModel();
     cm.CompanyName = ConfigurationManager.AppSettings["CompanyName"];
     cm.AppName = " - " + ConfigurationManager.AppSettings["AppName"];
     cm.AppVersion = " " + ConfigurationManager.AppSettings["AppVersion"];
     sb.Append("Web Security Administration Portal");
     ViewBag.Message = sb.ToString();
     return View();       
}

This is the model:

public class CompanyModel
{
    public string CompanyName { get; set; }
    public string AppName { get; set; }
    public string AppVersion { get; set; }
}

This is the partial view named "Company":

@model WebSecurityAdmin.Models.CompanyModel

<table>
   <tr>
      <td>@Html.DisplayNameFor(model => model.CompanyName)
          @Html.DisplayNameFor(model => model.AppName)
          @Html.DisplayNameFor(model => model.AppVersion)
      </td>
   </tr>
</table>

This is one of the views, let's say Default view where I want to embed my partial view:

@section featured {
<section class="featured">
    <div class="content-wrapper">
        <hgroup class="title">
            <h1>@Html.Partial("Company")</h1>
        </hgroup>
    </div>
</section>

}

When I display Default view I get property names of CompanyModel displayed instead of their values:

CompanyName AppName AppVersion

Why is that and please explain what I'm doing wrong.

Upvotes: 1

Views: 293

Answers (1)

krillgar
krillgar

Reputation: 12815

@Html.DisplayNameFor() is what's wrong. That displays either the name of the property, or the name you've given it through an attribute. Instead of that, just have your row like this:

<td>
    @model.CompanyName  
    @model.AppName  
    @model.AppVersion  
</td>

Edited: Adding @ before model

Another option is to use the helper @Html.DisplayFor(m => m.CompanyName) as depending on the type of property, especially ones more complex than a string or number, will utilize display templates and add large blocks of HTML in a very succinct manner that keeps your Razor view more readable.

Upvotes: 2

Related Questions