在 MVC5 中使用 Razor 呈现自定义控件



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

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 事件根本没有渲染。

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

我想我已经解决了。

我所做的代码更改如下。在 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 事件正确触发。

最新更新