【问题标题】:MVC Custom EditorForMVC 自定义编辑器For
【发布时间】:2012-11-04 08:01:42
【问题描述】:

我一直在试验 MVC(昨天开始),想知道是否可以创建我的“自定义控件”。

我有类似以下内容:

在我看来

@Html.EditorFor(model => model.UserName, "StringTemplate", new {LabelText = "Test" })

用于渲染控件的“自定义视图”

@model MvcApplication.Models.StringTemplate

@Html.LabelFor(model => model.Field, ViewData["LabelText"].ToString())
@Html.TextBoxFor(model => model.Field)

视图模型

public class RegisterModel
{
    [Required]
    public StringTemplate UserName { get; set; }
}

public class StringTemplate
{
    [Required]
    public string Field { get; set; }

    public StringTemplate()
    {
        Field = String.Empty;
    }

    public StringTemplate(string field)
    {
        Field = field;
    }
}

我想要做的是通过调用@Html.EditorFor,利用StringTemplate 并传递值LabelText。如何从视图“StringTemplate”中读取值“Test”?另外,有没有办法可以在“StringTemplate”视图中执行@Html.ValidationMessageFor()?

如果有任何教程或链接可以帮助我解决这个问题,我将不胜感激......

谢谢!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor html-helper


    【解决方案1】:

    我认为你让事情变得比他们需要的更难。您不必为您的编辑器模板创建自定义类来使用 - 只需使用一个字符串。

    所以在你的模型中:

    public class RegisterModel
    {
        [Required]
        public string UserName { get; set; }
    }
    

    您的模板看起来像这样(确保将其命名为“String.cshtml”):

    @model System.String
    
    @Html.LabelFor(model => model, (string)ViewData["LabelText"])
    @Html.TextBoxFor(model => model)
    

    那么在你看来:

    @Html.EditorFor(model => model.UserName, new {LabelText = "Test" })
    

    关于 ValidationMessageFor,这也可以添加到您的模板中:

    @Html.ValidationMessageFor(model => model)
    

    【讨论】:

    • 谢谢,这完美地回答了我的问题!
    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多