【问题标题】:Rendering custom controls using Razor in MVC5在 MVC5 中使用 Razor 渲染自定义控件
【发布时间】:2017-03-20 14:58:06
【问题描述】:

我有一个包含两个属性的视图模型。

public class ControlToRender
{
     public int IsText { get; set; }
     public string LabelString { get; set; } 
     public string TextValue { get; set; }
}

这被填充在控制器中,以便:

IsText = True;
LabelString = "please enter your name";
TextValue = "";

在我看来,我正在对上述内容进行如下测试:

if (Model.IsText)
{
    @Html.CtrlHelper().ClearableTextBoxFor(model => model.TextValue, 
          new
          {
                placeholder = Html.Encode(placeHolder),
                @class = "js-text-option-text",
                @onchange = "javascript:alert('excellent!!!')"})
}

最后,我的 HTML 帮助代码:

static void CreateClearableTextBoxFor(object htmlAttributes, 
            decimal? additionalCost, out IDictionary<string, object> attrs,  
            out string anchorHtml)
    {
        attrs = new RouteValueDictionary(htmlAttributes);
        if (attrs.ContainsKey("class"))
            attrs["class"] = String.Concat("js-text-option-clear ", attrs["class"]);
        else
            attrs.Add("class", "js-text-option-clear");

        var anchor = new TagBuilder("a");
        anchor.AddCssClass("js-text-option-clear-button text-option-clear js-toolTip tool-tip");
        anchor.Attributes.Add("title", "Clear");
        if (additionalCost != null && additionalCost > 0)
        {
            anchor.Attributes.Add("data-additionalcost", additionalCost.ToString());
        }
        anchorHtml = anchor.ToString();
    }

这段代码编译成功,并呈现在屏幕上,但是当我更改控件中的文本时,不会触发 onchange 事件。

我查看了生成的 hmtl 输出,发现 onchange 事件根本没有渲染。

有人可以指出正确的方向吗?

【问题讨论】:

    标签: javascript c# jquery asp.net-mvc html-helper


    【解决方案1】:

    我想我已经解决了。

    我所做的代码更改如下。在我添加的 HMTL 助手中:

    attrs = new RouteValueDictionary(htmlAttributes);
    if (attrs.ContainsKey("class"))
        attrs["class"] = String.Concat("js-text-option-clear ", attrs["class"]);
    else
        attrs.Add("class", "js-text-option-clear"); 
    
     /* NEW LINE BELOW */
     attrs.Add("onchange", "javascript:alert('Booooooom');");
    

    这会导致 onchange 事件正确触发。

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多