Reputation: 17701
I have got one label in view that i need to display value in that label and i have assigned value to that label in controller ..
and this is model
namespace MvcSampleApplication.Models
{
public class labelsdisplay
{
public string labelvalue { get; set; }
}
}
and this is my controller
namespace MvcSampleApplication.Controllers
{
public class LbelDisplayController : Controller
{
public ActionResult Index()
{
labelsdisplay lbldisx = new labelsdisplay();
string name = "ABC";
lbldisx.labelvalue = name;
return View(lbldisx);
}
}
}
and this the view (strongly typed view)
@model MvcSampleApplication.Models.labelsdisplay
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (@Html.BeginForm())
{
@Html.LabelFor(m=>m.labelvalue)
}
my problem is not able to display value("ABC") instead of that it displaying "labelvalue" in that label in view... would any one pls suggest any solutions ...on this....
Many thanks..
Upvotes: 2
Views: 12218
Reputation: 8380
Change
@Html.LabelFor(m=>m.labelvalue)
to
<label>@Model.labelvalue</label>
(or leave out the label tags, if you don't need them).
The @-operator will take whatever you give it and turn it into a string, HTML-encode that string (unless what you gave it was an IHtmlString) and render the encoded string in the output.
Html.LabelFor
, on the other hand, is intended to be used with a form model. Let's say you have a model like this
public class PersonForm
{
public string Firstname { get; set;}
public string Lastname { get; set;}
}
and an action medthod accepting this form as an argument:
public ActionResult CreatePerson(PersonForm form){
/* Create new person from form */
}
Now, in your view, to display a label for the Firstname
field, you use Html.LabelFor()
:
@model PersonForm
@Html.LabelFor(m => m.Firstname)
This will render something like <label for="Firstname">Firstname</label>
. If you instead wanted to render something like <label for="Firstname">Please enter firstname</label>
you would attach an attribute to the Firstname
property:
public class PersonForm
{
[Display(Name = "Please enter firstname")]
public string Firstname { get; set;}
[Display(Name = "Please enter lastname")]
public string Lastname { get; set;}
}
where the attributes are from the System.ComponentModel.DataAnnotations
namespace.
Upvotes: 3
Reputation: 54541
To display just the value, you can use
@Html.DisplayNameFor(m=>m.labelvalue)
Or if you want to display the label element with value, you can use
@Html.LabelFor(m=>m.labelvalue, Model.labelvalue)
The first param is the value of the name, and the 2nd param is the value of the label.
Upvotes: 4