我尝试这样做时出现模板错误?
我正在使用asp.net mvc 3并且我一直收到此错误,因为我没有使用模板,所以我不理解它。
我在局部视野中有这个
@model ViewModels.FormViewModel @Html.TextBoxFor(x => x.Due.ToShortDateString())
在我的viewmodel中
public class FormViewModel { public DateTime Due { get; set; } public FormViewModel() { DueDate = DateTime.UtcNow; } }
我收到这个错误
模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。 描述:执行当前Web请求期间发生未处理的exception。 请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
exception详细信息:System.InvalidOperationException:模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。
应该是这样的:
@Html.TextBoxFor(x => x.Due)
如果你想要这个日期的格式:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime Due { get; set; }
然后:
@Html.EditorFor(x => x.Due)
如果你真的想要使用这个.ToShortDateString()
方法,你需要使用非强类型的帮助器(显然我会建议这样做):
@Html.TextBox("Due", Model.Due.ToShortDateString())
有一个重载可以帮助实现这一点,同时保持强类型。
// Specify that you're providing the format argument (string) @Html.TextBoxFor(x => x.Due, format: Model.Due.ToShortDateString()) // Or use the overload with format and html options, where null is the htmloptions @Html.TextBoxFor(x => x.Due, Model.Due.ToShortDateString(), null)
你得到错误是因为.TextBoxFor()
html助手正在使用内置模板(字符串输入的文本框),并且你给它一个太复杂的lambda表达式(即不属于该集合)消息中列出的类型)。
要解决此问题,请将要编辑的属性的类型更改为string
,以便MVC可以使用默认字符串模板,或者让MVC使用默认的日期时间模板。 我推荐后者:
@Html.TextBoxFor(m => m.Due)
如果您对用户被要求编辑日期的方式不满意,请在〜/ Views / Shared / EditorTemplates中放置一个名为“DateTime.cshtml”的部分视图,您可以在其中构建编辑器,使其按您希望的方式工作。
如果您使用MVC并具有内联代码元素,请尝试设置如下参数 –
@{ string parameterValue = DateTime.Parse(@item.Value).ToShortDateString(); } @Html.DisplayFor(model => parameterValue)
您通过在textboxfor
的参数中传递方法而不是传递表达式来误导应用程序。
你有过 :
@Html.TextBoxFor(x => x.Due.ToShortDateString())
将结果存储在变量中,然后使用表达式。 试试这个
var shortDate = Model.Due.ToShortDateString(); @Html.TextBoxFor(x => shortDate )
而不是在模型中添加格式使用@Value Annotations如下所示
@ Html.TextBoxFor(x => x.Due new {@ Value = Model.Due.ToShortDateString()})