【问题标题】:how to display label in a view value coming from view如何在来自视图的视图值中显示标签
【发布时间】:2013-08-01 04:02:51
【问题描述】:

我有一个标签,我需要在该标签中显示值,并且我已在控制器中为该标签分配值..

这是模型

 namespace MvcSampleApplication.Models
 {    
     public class labelsdisplay
     {
        public string labelvalue { get; set; }    
     }
 }

这是我的控制器

namespace MvcSampleApplication.Controllers
{
    public class LbelDisplayController : Controller
    {               
        public ActionResult Index()
        {
            labelsdisplay lbldisx = new labelsdisplay();
            string name = "ABC";
            lbldisx.labelvalue = name;       
            return View(lbldisx);
        }    
    }
}

这就是视图(强类型视图)

 @model MvcSampleApplication.Models.labelsdisplay
@{
    ViewBag.Title = "Index";
}    
<h2>Index</h2>
@using (@Html.BeginForm())
{     
    @Html.LabelFor(m=>m.labelvalue)    
}

我的问题是无法显示值(“ABC”),而不是在视图中的该标签中显示“labelvalue”... 任何人都可以提出任何解决方案......关于这个......

非常感谢..

【问题讨论】:

  • 您真的需要label 元素还是只想显示值?
  • 我不确定通常在 Web 应用程序中我们确实使用标签,但在 mvc 中是否有任何其他方法..

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

要只显示值,您可以使用

@Html.DisplayNameFor(m=>m.labelvalue)

或者如果你想显示带有值的标签元素,你可以使用

@Html.LabelFor(m=>m.labelvalue, Model.labelvalue)  

第一个参数是名称的值,第二个参数是标签的值。

【讨论】:

    【解决方案2】:

    改变

    @Html.LabelFor(m=>m.labelvalue)
    

    <label>@Model.labelvalue</label>
    

    (如果不需要,也可以省略标签标签)。

    @-operator 将获取您给它的任何内容并将其转换为字符串,对该字符串进行 HTML 编码(除非您给它的是 IHtmlString)并在输出中呈现编码的字符串。

    另一方面,Html.LabelFor 旨在与表单模型一起使用。假设你有一个这样的模型

    public class PersonForm
    {
      public string Firstname { get; set;}
      public string Lastname { get; set;}
    }
    

    以及接受这种形式作为参数的动作方法:

    public ActionResult CreatePerson(PersonForm form){
      /* Create new person from form */
    }
    

    现在,在您看来,要显示Firstname 字段的标签,您可以使用Html.LabelFor()

    @model PersonForm
    
    @Html.LabelFor(m => m.Firstname)
    

    这将呈现类似&lt;label for="Firstname"&gt;Firstname&lt;/label&gt; 的内容。如果你想渲染类似&lt;label for="Firstname"&gt;Please enter firstname&lt;/label&gt; 的东西,你可以为Firstname 属性附加一个属性:

    public class PersonForm
    {
      [Display(Name = "Please enter firstname")]
      public string Firstname { get; set;}
    
      [Display(Name = "Please enter lastname")]
      public string Lastname { get; set;}
    }
    

    其中的属性来自 System.ComponentModel.DataAnnotations 命名空间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 2018-04-05
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多