3

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

@Html.TextBoxFor(m => m.Model1.field1, new { @class = "login-input", @name="Name",  @Value = "test" })

我想将此文本框的默认值从“文本”更改为存储在模型字段中的值。如何将模型字段设置为值属性?假设要调用的模型名称是Model2,属性是field2。如何将文本框的值设置为 field2?

4

3 回答 3

1

您必须首先编写一个扩展方法,如下所示:

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"});
    }

}
于 2012-12-03T19:21:34.277 回答
0

在您的控制器中,field1在将其传递给视图之前设置它的值......这将自动设置该值。如果您在另一个字段中有值,只需执行以下操作:

model.field1 = model.field2;

在你的控制器中......这样模型就有了一致的数据。

如果您不需要/不希望默认值实际上是文本框的值,您也可以使用PlaceHolder... 这样用户可以将值视为提示,但它不会算作文本框内容一旦您发布表格。

@Html.TextBoxFor(m => m.Model1.field1, new { @class = "login-input", @name="Name",  placeholder= "test" })

请记住,并非 HtmlAttributes 中的所有字段名都需要“@”...@class是正确的,但我认为不需要其他字段名。

于 2012-12-03T19:28:11.893 回答
0

您可以在将模型传递给视图之前在控制器操作中设置默认值:

model.field1 = "Test"
return View(model)
于 2013-04-29T15:06:57.177 回答