我有一个使用创建的文本框
@Html.TextBoxFor(m => m.Model1.field1, new { @class = "login-input", @name="Name", @Value = "test" })
我想将此文本框的默认值从“文本”更改为存储在模型字段中的值。如何将模型字段设置为值属性?假设要调用的模型的名称是 Model2,属性是 field2。如何将文本框的值设置为 field2?
最佳答案
您必须首先编写一个扩展方法,如下所示:
public class ObjectExtensions
{
public static string Item<TItem, TMember>(this TItem obj, Expression<Func<TItem, TMember>> expression)
{
if (expression.Body is MemberExpression)
{
return ((MemberExpression)(expression.Body)).Member.Name;
}
if (expression.Body is UnaryExpression)
{
return ((MemberExpression)((UnaryExpression)(expression.Body)).Operand).Member.Name;
}
if (expression.Body is ParameterExpression)
{
return expression.Body.Type.Name;
}
throw new InvalidOperationException();
}
}
当你这样写时,它会提取属性的名称:@Html.TextBoxFor(m => m.Model1.field1)
然后你可以像这样使用它:
Html.TextBoxFor(m => m.Model1.field1,
new { @class = "login-input",
@name="Name",
@value = Model.Item(m => m.Model1.field1) })
如果您不想再次调用 m => m.Model1.field1
,则必须声明您的 TextBoxFor
方法版本,该版本更复杂,但如果你想要我可以为你提供详细信息。
这是我的代码库 Github 中的示例:
public static class HtmlHelperExtensionForEditorForDateTime
{
public static MvcHtmlString Editor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string propname = html.ViewData.Model.Item(expression);
string incomingValue = null;
var httpCookie = html.ViewContext.RequestContext.HttpContext.Request.Cookies["lang"];
if (metadata.Model is DateTime && (httpCookie.IsNull() || httpCookie.Value == Cultures.Persian))
incomingValue = PersianCalendarUtility.ConvertToPersian(((DateTime)metadata.Model).ToShortDateString());
if (string.IsNullOrEmpty(incomingValue))
return html.TextBox(propname, null, new { @class = "datepicker TextField" });
return html.TextBox(propname, incomingValue, new { @class = "datepicker TextField"});
}
}
关于asp.net-mvc-3 - MVC3 从模型中设置文本框的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13689796/