[英]Rendering custom controls using Razor in MVC5
我有一个包含两个属性的视图模型。
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事件正确触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.