asp.net-mvc-3 - MVC3 从模型中设置文本框的默认值

标签 asp.net-mvc-3 default-value html.textboxfor

我有一个使用创建的文本框

@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/

相关文章:

变量未被替换

dependency-injection - 库项目中构造函数参数的默认值

c# - Rfc2898DeriveBytes 类的 iterationCount 属性的默认值是多少

asp.net-mvc - MVC中的TextBoxFor如何限制为2位小数?

asp.net-mvc - ASP.NET MVC中的Razor页面生命周期

javascript - 使用 Jquery 的部分 View 渲染顺序

asp.net-mvc-3 - 如何让Html.DisplayFor显示换行符?

asp.net-mvc-3 - 在 ASP.NET MVC 3 中应用数据注释时,你打算如何使用提示、描述、排序