Double input mvc extension

风格不统一 提交于 2019-12-11 13:52:19

问题


Here I was trying to make an extension with double input boxes

the returned model's properties are null, They are not correctly bound or there is another issue here, please help me on writing this extension and make use of it. I need to use thousands of it during my code.

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

The Model class

public class DoubleNumber
{
    public int Num1 { get; set; } // tried strings but again they are null
    public int Num2 { get; set; }
}

And Here is the controller -Post action which we need the entered numbers

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

回答1:


You'd probably have an easier time just using an editor template:

Views\Shared\EditorTemplates\DoubleNumber.cshtml

@model DoubleNumber
@Html.TextBoxFor(m => m.Num1)
@Html.TextBoxFor(m => m.Num2)

Then, in your view:

@Html.EditorForModel()

Or, if you've got a property of type DoubleNumber on a view model:

@Html.EditorFor(m => m.MyDoubleNumberProperty)


来源:https://stackoverflow.com/questions/23731814/double-input-mvc-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!