m.ShortName, new { @class = "form-control", @place-6ren">
gpt4 book ai didi

asp.net-mvc - 如何将 "required"属性添加到 mvc razor View 模型文本输入编辑器

转载 作者:行者123 更新时间:2023-12-02 04:44:53 25 4
gpt4 key购买 nike

我有以下 MVC 5 Razor HTML 助手:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", @placeholder = "short name"})

我需要这个字段是必需的(即当用户在没有放置 value inn 的情况下导航时有一个红色轮廓)。在 WebForms HTML 5 中,我只能说 <input type="text" required />达到这个效果。
在 Razor 语法中完成此操作的正确语法是什么?

最佳答案

您可以使用 required html 属性,如果你想要:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", placeholder = "short name", required="required"})

或者您可以使用 RequiredAttribute .Net 中的类。使用 jQuery RequiredAttribute可以在前端和服务器端进行验证。如果你想走 MVC 路线,我建议阅读 Data annotations MVC3 Required attribute .

或者

你可以变得非常先进:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));

attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");

if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}

@Html.TextBoxFor(m => m.ShortName, attributes)

}

或者如果您需要它用于多个编辑器模板:
public static class ViewPageExtensions
{
public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
instance.Html.GetUnobtrusiveValidationAttributes(
instance.ViewData.TemplateInfo.HtmlFieldPrefix));

if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
}
}

然后在您的模板中:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = this.GetAttributes();

attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");

@Html.TextBoxFor(m => m.ShortName, attributes)

}

更新 1(适用于不熟悉 ViewData 的 Tomas)。

What's the difference between ViewData and ViewBag?

摘抄:

So basically it (ViewBag) replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

关于asp.net-mvc - 如何将 "required"属性添加到 mvc razor View 模型文本输入编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23071795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com