我正在使用 cshtml/c#/css/javascript 的组合来创建一个网页,这是我完全陌生的,所以欢迎任何提示。
C# 文件创建一个部分类,这是一个示例片段
[Required]
[Display(Name = "First Name *")] //First Name * is displayed on actual page
public string FirstName{ get; set; }
cshtml 文件创建所有必要的容器、标签和段落。 css 包含所有样式。 javascript 增强了网页功能。
所以,这是一个交易:我需要添加 *,对于所有必需的元素,它应该都是红色的。我可以遍历所有可能的页面并手动将它们添加到每个元素,但我想是否可以优化代码。
是否可以创建类似下面的伪代码?
if variable has a required flag set to it //from c# file
add stylized red * next to the label
非常感谢任何帮助!
更新
我修改了下面提供的文章中的代码,但是,这是我一直遇到的另一个问题。这是我的助手修改后的代码:
public static MvcHtmlString EditorEntryFor<TModel, TValue>(
this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
return BuildFormEntry(html.LabelWithRequiredMarkerFor(expression),
html.EditorFor(expression), html.ValidationMessageFor(expression));
//return BuildFormEntry(html.LabelWithRequiredMarkerFor(expression),
// html.TextAreaFor(expression), html.ValidationMessageFor(expression));
}
private static MvcHtmlString LabelWithRequiredMarkerFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression)
{
var label = html.LabelFor(expression);
if (ModelMetadata.FromLambdaExpression(expression, html.ViewData).IsRequired)
{
label = new MvcHtmlString(label.ToString().Substring(0, label.ToString().Length - 8).Trim() +
"<span style=\"color:red\" class=\"required-marker\">*</span></label>");
}
return label;
}
private static MvcHtmlString BuildFormEntry(
MvcHtmlString label, MvcHtmlString input, MvcHtmlString validation)
{
return new MvcHtmlString("<div class=\"editor-label\">" + label + "</div>\n" +
"<div class=\"editor-field\">" + input + validation + "</div>\n\n");
//return new MvcHtmlString("<div class=\"editor-label\">" + label + "</div>\n");
}
方法调用与LabelFor完全一样:
Html.EditorEntryFor(model => model.Project.FirstName)
//**equals to**
Html.LabelFor(model => model.Project.FirstName)
现在我希望 EditorEntryFor 中的表达式如下所示:
Html.EditorEntryFor(model => model.Project.FirstName, new { @title = "Enter firstname." })
但是,助手只接受一个参数表达式,我希望表达式值等于 model => model.Project.FirstName, new { @title = "Enter firstname."})
但是,Visual Studio 总是认为我尝试输入第二个参数。 有没有办法强制表达式认为“,”是表达式的一部分而不是第二个参数?到目前为止,看起来正常的字符串操作都无法解决问题 =(
非常感谢大家!
最佳答案
除了已经提供的解决方案外,我还找到了一些非常有用的文章,它们极大地帮助了我实现所需的内容:html helper with required fields , html helper
关于javascript - 用cshtml/c#/css/javascript优化网页样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557148/