我试图用双输入框
进行扩展返回的模型的属性为null, 他们没有正确绑定或这里有另一个问题, 请帮我写这个扩展并使用它。 我需要在代码中使用数千个。
public static class DoubleBoxHelper
{
public static MvcHtmlString DoubleBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
//int id,
Expression<Func<TModel, TProperty>> expression)
{
var builder = new StringBuilder();
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var model = metadata.Model as DoubleNumber;
var name = ExpressionHelper.GetExpressionText(expression);
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
var fieldId = TagBuilder.CreateSanitizedId(fullName);
// 1st TextBox
var tagInputLeft = new TagBuilder("input");
tagInputLeft.Attributes.Add("name", fullName);
tagInputLeft.Attributes.Add("id", fieldId + 1);
tagInputLeft.Attributes.Add("type", "text");
tagInputLeft.Attributes.Add("value", model.Num1 == null ? "" : model.Num1.ToString());
// 2nd TextBox
var tagInputRight = new TagBuilder("input");
tagInputRight.Attributes.Add("name", fullName);
tagInputRight.Attributes.Add("id", fieldId + 2);
tagInputRight.Attributes.Add("type", "text");
tagInputRight.Attributes.Add("value", model.Num2 == null ? "" : model.Num2.ToString());
builder.Append(tagInputLeft.ToString(TagRenderMode.SelfClosing));
builder.Append(tagInputLeft.ToString(TagRenderMode.SelfClosing));
return new MvcHtmlString(builder.ToString());
}
}
模型类
public class DoubleNumber
{
public int Num1 { get; set; } // tried strings but again they are null
public int Num2 { get; set; }
}
这是控制器-Post动作,我们需要输入的数字
[HttpPost]
public ActionResult Index(DoubleNumber g)
{
int iNum1 = g.Num1; // int or string doesn't matter, it couldn't get the entered(modified) model
int iNum2 = g.Num2;
var vm = ViewModelOf(g);
return View(vm);
}
答案 0 :(得分:2)
使用编辑器模板可能会更轻松:
<强>视图\共享\ EditorTemplates \ DoubleNumber.cshtml 强>
@model DoubleNumber
@Html.TextBoxFor(m => m.Num1)
@Html.TextBoxFor(m => m.Num2)
然后,在您看来:
@Html.EditorForModel()
或者,如果您在视图模型上有DoubleNumber
类型的属性:
@Html.EditorFor(m => m.MyDoubleNumberProperty)