我正在使用asp.net mvc 3并且我一直收到此错误,因为我没有使用模板,所以我不理解它。
我在部分视图中有这个
@model ViewModels.FormViewModel
<div="tabs-1">
@Html.TextBoxFor(x => x.Due.ToShortDateString())
</div>
在我的viewmodel中
public class FormViewModel
{
public DateTime Due { get; set; }
public FormViewModel()
{
DueDate = DateTime.UtcNow;
}
}
我收到此错误
模板只能用于字段 访问,财产访问, 单维数组索引,或 单参数自定义索引器 表达式。描述:未处理 期间发生了异常 执行当前的Web请求。 请查看堆栈跟踪了解更多信息 有关错误的信息和位置 它起源于代码。
异常详细信息: System.InvalidOperationException: 模板只能与字段一起使用 访问,财产访问, 单维数组索引,或 单参数自定义索引器 表达式。
答案 0 :(得分:51)
应该是这样的:
@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())
答案 1 :(得分:6)
有一个重载可以帮助实现这一点,同时保持强类型。
// 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)
答案 2 :(得分:5)
您收到错误是因为.TextBoxFor()
html助手正在使用内置模板(字符串输入的文本框),并且您给它一个过于复杂的lambda表达式(即不属于消息中列出的类型集。)
要解决此问题,请将要编辑的属性类型更改为string
,以便MVC可以使用默认字符串模板,或者让MVC使用默认的日期时间模板。我推荐后者:
@Html.TextBoxFor(m => m.Due)
如果您对用户被要求编辑日期的方式不满意,请在〜/ Views / Shared / EditorTemplates中放置一个名为“DateTime.cshtml”的部分视图,您可以在其中构建编辑器,使其按您的方式工作想。
答案 3 :(得分:5)
如果您使用 MVC 并且具有内联代码元素,请尝试设置这样的参数 -
@{
string parameterValue = DateTime.Parse(@item.Value).ToShortDateString();
}
@Html.DisplayFor(model => parameterValue)
答案 4 :(得分:0)
您通过在textboxfor
参数中传递方法而不是传递表达式来误导应用程序。
你有:
@Html.TextBoxFor(x => x.Due.ToShortDateString())
将结果存储在变量中,然后使用表达式。试试这个
var shortDate = Model.Due.ToShortDateString();
@Html.TextBoxFor(x => shortDate )
答案 5 :(得分:0)
而不是在模型中添加格式使用@Value Annotations如下
@ Html.TextBoxFor(x =&gt; x.Due new {@ Value = Model.Due.ToShortDateString()})