Knockout.js:无法绑定到自定义@ Html.EditorFor

时间:2012-04-19 18:23:13

标签: asp.net-mvc asp.net-mvc-3 knockout.js knockout-2.0

我正在使用一个选择器来构建一个自定义的@ Html.EditorFor(称为@ Html.FullFieldEditor)。它确定要生成的输入类型(文本框,下拉列表,单选按钮,复选框等)。我一直试图把它挂成一个单选按钮列表,因此:

@Html.FullFieldEditor(m => m.MyModel.MyRadioButton, new Dictionary<string, object> { { "data_bind", "myRadioButton" } })

或者像这样:

@Html.FullFieldEditor(m => m.MyModel.MyRadioButton, new { data_bind = "checked: myRadioButton" })

但没有运气。

我正在尝试修复我的selector.cshtml代码,但结果只是制造了可怕的混乱。以下是在我尝试实施knockout.js之前为我工作的代码:

@{
var supportsMany = typeof (IEnumerable).IsAssignableFrom(ViewData.ModelMetadata.ModelType);
var selectorModel = (Selector)ViewData.ModelMetadata.AdditionalValues["SelectorModelMetadata"];
var fieldName = ViewData.TemplateInfo.GetFullHtmlFieldName("");
var validationClass = ViewData.ModelState.IsValidField(fieldName) ? "" : "input-validation-error";


// Loop through the items and make sure they are Selected if the value has been posted
if(Model != null)
{
    foreach (var item in selectorModel.Items)
    {
        if (supportsMany)
        {
            var modelStateValue = GetModelStateValue<string[]>(Html, fieldName) ?? ((IEnumerable)Model).OfType<object>().Select(m => m.ToString());
            item.Selected = modelStateValue.Contains(item.Value);
        }
        else
        {
            var modelStateValue = GetModelStateValue<string>(Html, fieldName);
            if (modelStateValue != null)
            {
                item.Selected = modelStateValue.Equals(item.Value, StringComparison.OrdinalIgnoreCase);
            }
            else
            {
                Type modelType = Model.GetType();
                if (modelType.IsEnum)
                {
                    item.Selected = item.Value == Model.ToString();
                }
            }
        }
    }
}
}
@functions
{
    public MvcHtmlString BuildInput(string fieldName, 
    SelectListItem item, string inputType, object htmlAttributes) 
    // UPDATE: Trying to do it above
    {
    var id = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value);
    var wrapper = new TagBuilder("div");
    wrapper.AddCssClass("selector-item");

    var input = new TagBuilder("input");
    input.MergeAttribute("type", inputType);
    input.MergeAttribute("name", fieldName);
    input.MergeAttribute("value", item.Value);
    input.MergeAttribute("id", id);

    input.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 
    // UPDATE: and trying above, but see below in the 
    // @foreach...@BuildInput section

    input.MergeAttributes(Html.GetUnobtrusiveValidationAttributes(fieldName, ViewData.ModelMetadata));

    if(item.Selected)
        input.MergeAttribute("checked", "checked");

    wrapper.InnerHtml += input.ToString(TagRenderMode.SelfClosing);


    var label = new TagBuilder("label");
    label.MergeAttribute("for", id);
    label.InnerHtml = item.Text;
    wrapper.InnerHtml += label;

    return new MvcHtmlString(wrapper.ToString());
}

/// <summary>
/// Get the raw value from model state
/// </summary>
public static T GetModelStateValue<T>(HtmlHelper helper, string key)
{
    ModelState modelState;
    if (helper.ViewData.ModelState.TryGetValue(key, out modelState) && modelState.Value != null)
        return (T)modelState.Value.ConvertTo(typeof(T), null);
    return default(T);
}
}
@if (ViewData.ModelMetadata.IsReadOnly)
{
var readonlyText = selectorModel.Items.Where(i => i.Selected).ToDelimitedString(i => i.Text);
if (string.IsNullOrWhiteSpace(readonlyText))
{
    readonlyText = selectorModel.OptionLabel ?? "Not Set";
}

@readonlyText

foreach (var item in selectorModel.Items.Where(i => i.Selected))
{
@Html.Hidden(fieldName, item.Value)
}
}
else
{
if (selectorModel.AllowMultipleSelection)
{
    if (selectorModel.Items.Count() < selectorModel.BulkSelectionThreshold)
    {
<div class="@validationClass">
    @foreach (var item in selectorModel.Items)
            {
        @BuildInput(fieldName, item, "checkbox") // throwing error here if I leave this as is (needs 4 arguments)
        //But if I do this:
        //@BuildInput(fieldName, item, "checkbox", htmlAttributes) // I get does not exit in current context

            }
</div>
    }
    else
    {
@Html.ListBox("", selectorModel.Items)
    }
}
else if (selectorModel.Items.Count() < selectorModel.BulkSelectionThreshold)
{
<div class="@validationClass">
    @*@if (selectorModel.OptionLabel != null)
        {
        @BuildInput(fieldName, new SelectListItem { Text = selectorModel.OptionLabel, Value = "" }, "radio")
        }*@
    @foreach (var item in selectorModel.Items)
        {
        @BuildInput(fieldName, item, "radio")//same here
        }
</div>
}
else
{
@Html.DropDownList("", selectorModel.Items, selectorModel.OptionLabel)
}
}

非常感谢任何帮助。

修改 我试图最小化现有的JS代码(超过1500行)以显示/隐藏KO(它似乎能够显着减少代码)。我知道我已经有了KO的选择(visibleif等),但假设我想用KO实现的目标是可行的,我可以选择visible。无论如何,越过绑定障碍阻止我走得那么远。

以下是我使用普通JS显示/隐藏的一些代码示例:

$(document).ready(function () {
    $("input[name$='MyModel.MyRadioButton']").click(function () {
        var radio_value = $(this).val();
        if (radio_value == '1') {
            $("#MyRadioButton_1").show();
            $("#MyRadioButton_2").hide();
            $("#MyRadioButton_3").hide();
        }
        else if (radio_value == '2') {
            $("#MyRadioButton_1").show();
            $("#MyRadioButton_2").hide();
            $("#MyRadioButton_3").hide();
        }
        else if (radio_value == '3') {
            $("#MyRadioButton_1").show();
            $("#MyRadioButton_2").hide();
            $("#MyRadioButton_3").hide();
        }
    });
    $("#MyRadioButton_1").hide();
    $("#MyRadioButton_2").hide();
    $("#MyRadioButton_3").hide();
});

我认为KO可以将上述内容降至最低。同样,我正在考虑20-30个输入,大多数有3个以上的选择(少数在下拉中有10个选项)。这很难维持在1500线并且不断增长。

然后在我的view中,我得到了这个:

<div id="MyRadioButton_1">
    @Helpers.StartingCost(MyModel.Choice1, "1")
</div>
<div id="MyRadioButton_2">
    @Helpers.StartingCost(MyModel.Choice2, "2")
</div>
<div id="MyRadioButton_3">
    @Helpers.StartingCost(MyModel.Choice2, "2")
</div>

上面的view代码会随KO略有变化,但我的JS代码也会随着我的努力而减少。

编辑2 这是FullFieldEditor代码的一部分。为简洁起见,省略了部分内容(例如RequiredForToolTipForSpacerFor的代码。

public static MvcHtmlString FullFieldEditor<T, TValue>(this HtmlHelper<T> html, Expression<Func<T, TValue>> expression)
    {
        return FullFieldEditor(html, expression, null);
    }

    public static MvcHtmlString FullFieldEditor<T, TValue>(this HtmlHelper<T> html, Expression<Func<T, TValue>> expression, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

        if (!metadata.ShowForEdit)
        {
            return MvcHtmlString.Empty;
        }

        if (metadata.HideSurroundingHtml)
        {
            return html.EditorFor(expression);
        }

        var wrapper = new TagBuilder("div");
        wrapper.AddCssClass("field-wrapper");
        var table = new TagBuilder("table");
        table.Attributes["border"] = "0";
        table.Attributes["width"] = "100%";//added this to even out table columns
        var tbody = new TagBuilder("tbody");
        var tr = new TagBuilder("tr");
        var td1 = new TagBuilder("td");
        td1.Attributes["width"] = "40%";
        td1.Attributes["valign"] = "top";
        var label = new TagBuilder("div");
        label.AddCssClass("field-label");
        label.AddCssClass("mylabelstyle");
        label.InnerHtml += html.MyLabelFor(expression);
        td1.InnerHtml = label.ToString();
        var td2 = new TagBuilder("td");
        td2.Attributes["width"] = "50%";
        td2.Attributes["valign"] = "top";
        var input = new TagBuilder("div");
        input.AddCssClass("field-input");

        input.InnerHtml += html.EditorFor(expression);
        td2.InnerHtml = input.ToString();
        var td3 = new TagBuilder("td");
        td3.Attributes["width"] = "5%";
        td3.Attributes["valign"] = "top";
        if (metadata.IsRequired && !metadata.IsReadOnly)
        {
            td3.InnerHtml += html.RequiredFor(expression);
        }
        var td4 = new TagBuilder("td");
        td4.Attributes["width"] = "5%";
        td4.Attributes["valign"] = "middle";
        if (!string.IsNullOrEmpty(metadata.Description))
        {
            td4.InnerHtml += html.TooltipFor(expression);
        }
        else td4.InnerHtml += html.SpacerFor(expression);
        td4.InnerHtml += html.ValidationMessageFor(expression);
        tr.InnerHtml = td1.ToString() + td2.ToString() + td3.ToString() + td4.ToString();
        tbody.InnerHtml = tr.ToString();
        table.InnerHtml = tbody.ToString();
        wrapper.InnerHtml = table.ToString();
        return new MvcHtmlString(wrapper + Environment.NewLine);
    }

更新3 选项不起作用。选项1甚至不会在data-bind中显示<input>。选项2不起作用,因为它只是检查是否需要该字段(代码只显示“必需”图像,如果是)。

当我在“UPDATE2”input.MergeAttributes(new RouteValueDictionary(htmlAttributes));)之前尝试了第一个建议时,这就是输出:

<div class="field-input" data_bind="checked: MyRadioButton">
    <div class="">
        <div class="selector-item">
            <input id="MyModel_MyRadioButton_Choice1" name="MyModel.MyRadioButton" type="radio" value="Choice1">
            <label for="MyModel_MyRadioButton_Choice1">I am thinking about Choice 1.</label>
        </div>
        <!--Just showing one radio button for brevity-->
    </div>
</div>

由于我将该属性与input的{​​{1}}部分合并,后者正在输出TagBuilder field-input,这就是它所在的位置(这是合乎逻辑的)。请注意,它应该是<div>,但在data-bind类中显示为data_bind。这就是我field-input

的方法
FullFieldEditor

我认为应该出现的是什么:

@Html.FullFieldEditor(m => m.MyModel.MyRadioButton, new Dictionary<string, object> { { "data_bind", "myRadioButton" } })

我怀疑我必须将<div class="field-input"> <div class=""> <div class="selector-item"> <!-- "data-bind" should be showing up in the following INPUT, correct?--> <input data-bind="checked: MyRadioButton" id="MyModel_MyRadioButton_Choice1" name="MyModel.MyRadioButton" type="radio" value="Choice1"> <label for="MyModel_MyRadioButton_Choice1">I am thinking about Choice 1.</label> </div> <!--Just showing one radio button for brevity--> </div> </div> 放入上面的htmlAttributes,而不是Selector.cshtml文件中。 HtmlFormHelper.cs是显示例如下拉列表,单选按钮列表或复选框列表(等等)之间的决定。 Selector.cshtmlSelector.cshtml文件夹中的模板。

对于背景:我有几十种表示数十页(或向导)的数百个输入。我正在使用Shared\EditorTemplates,因为它比每种类型的输入(下拉菜单,复选框,单选按钮等)都有意大利面条代码更容易维护。

更新4 仍然没有工作。

我在@Html.FullFieldEditor(其Selector.cshtml函数)代码中尝试了此操作,并且能够将“数据绑定”放入列表中每个单选按钮的BuildInput标记中:

<input>

然后我在相同的文件中执行此操作:

input.MergeAttribute("data-bind", htmlAttributes);

我的HTML输出是这样的:

@foreach (var item in selectorModel.Items)
    {
        @BuildInput(fieldName, item, "radio", "test")
    }

这使我相信它是<div class="selector-item"> <input data-bind="test" id="MyModel_MyRadioButton_Choice1" name="MyModel.MyRadioButton" type="radio" value="Choice1"> <label for="MyModel_MyRadioButton_Choice1">Choice 1</label> </div> 文件,而不是Selector.cshtml文件。

我要向所有人开放奖金50 +。

2 个答案:

答案 0 :(得分:4)

<强> UPDATE3

对下划线位置的第一次好评,我完全忘记了这一点。你的代码看起来几乎是正确的,但实际应该是这样的:

@Html.FullFieldEditor(m => m.MyModel.MyRadioButton, new Dictionary<string, object> { { "data_bind", "checked:myRadioButton" } })

因此,由于您在复选框和文本之间动态选择,因此您必须做一些事情。如果是一个复选框,则必须使用上面的代码。如果是文本框,则必须使用:

@Html.FullFieldEditor(m => m.MyModel.MyTextBox, new Dictionary<string, object> { { "data_bind", "value:MyTextBox" } })

<强> UPDATE2

所以我更新了你的代码,我 认为 数据绑定属于你的html(标记为option1和option2)。如果您给我一个生成的html片段以及您需要数据绑定的位置,那将会有所帮助。

public static MvcHtmlString FullFieldEditor<T, TValue>(this HtmlHelper<T> html, Expression<Func<T, TValue>> expression)
{
    return FullFieldEditor(html, expression, null);
}

public static MvcHtmlString FullFieldEditor<T, TValue>(this HtmlHelper<T> html, Expression<Func<T, TValue>> expression, object htmlAttributes)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

    if (!metadata.ShowForEdit)
    {
        return MvcHtmlString.Empty;
    }

    if (metadata.HideSurroundingHtml)
    {
        return html.EditorFor(expression);
    }

    var wrapper = new TagBuilder("div");
    wrapper.AddCssClass("field-wrapper");

    var table = new TagBuilder("table");
    table.Attributes["border"] = "0";

    //added this to even out table columns
    table.Attributes["width"] = "100%";

    var tbody = new TagBuilder("tbody");

    var td1 = new TagBuilder("td");
    td1.Attributes["width"] = "40%";
    td1.Attributes["valign"] = "top";

    var label = new TagBuilder("div");
    label.AddCssClass("field-label");
    label.AddCssClass("mylabelstyle");
    label.InnerHtml += html.MyLabelFor(expression);

    td1.InnerHtml = label.ToString();

    var td2 = new TagBuilder("td");
    td2.Attributes["width"] = "50%";
    td2.Attributes["valign"] = "top";

    var input = new TagBuilder("div");
    input.AddCssClass("field-input");

    // option1
    input.InnerHtml += html.EditorFor(expression, htmlAttributes);
    td2.InnerHtml = input.ToString();

    var td3 = new TagBuilder("td");
    td3.Attributes["width"] = "5%";
    td3.Attributes["valign"] = "top";

    if (metadata.IsRequired && !metadata.IsReadOnly)
    {
        // option2
        td3.InnerHtml += html.RequiredFor(expression, htmlAttributes);
    }

    var td4 = new TagBuilder("td");
    td4.Attributes["width"] = "5%";
    td4.Attributes["valign"] = "middle";

    if (!string.IsNullOrEmpty(metadata.Description))
    {
        td4.InnerHtml += html.TooltipFor(expression);
    }
    else
    {
        td4.InnerHtml += html.SpacerFor(expression);
    }

    td4.InnerHtml += html.ValidationMessageFor(expression);

    var tr = new TagBuilder("tr");
    tr.InnerHtml = td1.ToString() + td2.ToString() + td3.ToString() + td4.ToString();

    tbody.InnerHtml = tr.ToString();
    table.InnerHtml = tbody.ToString();
    wrapper.InnerHtml = table.ToString();

    return new MvcHtmlString(wrapper + Environment.NewLine);
}

<强>更新

虽然我仍然相信以下是“正确”的答案,但这是你的tagbuilder所缺少的,所以你可以传递自定义属性:

input.MergeAttributes(new RouteValueDictionary(htmlAttributes));

原始答案

我有一种感觉,试图混合剃刀和淘汰赛会发生什么,是剃刀的东西会渲染,然后当连接淘汰赛时,淘汰视图模型中的值将覆盖剃须刀视图中的任何内容

如果你想重构淘汰,这是我的建议:

  1. 创建一个仅限HTML的视图(没有剃刀)。
  2. 将敲除绑定添加到其中。
  3. 使用Json.NET以json对象的形式将模型数据传递给knockout。您可以通过多种方式执行此操作,但最简单的方法是将数据填充到javascript可以找到的<script>标记内的视图中。
  4. 使用Knockout Mapping将json对象加载到viewmodel中。

答案 1 :(得分:0)

不确定我是否理解你的困难。但是,如果您的困难在于何处以及如何根据您用于渲染属性的输入字段放置数据绑定 查看ClientBlocksMvc Controls Toolkit功能。它通过预编译模板(即显示页面片段的剃刀助手或部分视图)或完整视图自动计算大部分绑定。 那就是你可以写:@ Html.TextBoxFor(m =&gt; m.myProperty)和客户端ViewModel的文本框和myProperty之间的足够的数据绑定将被创建,依此类推,选择,无线电等。您还可以避免使用帮助程序,只需为文件提供“足够的名称”,并自动计算绑定。此外,您可以决定将服务器端ViewModel的一部分传输到客户端...您的客户端ViewmOdel将在post上自动传回服务器端ViewModel。