2012-10-22 69 views
1

我有这个输入元素,它与下划线模板效果很好。如何阻止HTML助手编码HTML元素的值属性?

<input id="color" name="color" value="<%= color %>" /> 

我想使用Html.Helper方法来生成元素。

我最初尝试只是基本的助手

@Html.TextBox("color", "<%= color %>") 

但是,这给了我

<input id="color" name="color" type="text" value="&lt;%= color %>" /> 

我试着包装的价值属性与Html.Raw但给出了同样的结果,以及环绕整个帮手结果在同样的事情。

整个块被包裹在<script type="text/template">标记中。

为什么它会将<转换为&lt;以及如何让它停止?

这工作,但

@MvcHtmlString.Create(Html.TextBox("color", "<%= color %>").ToString().Replace("&lt;", "<")) 
+0

因为属性值应该被编码。 – SLaks

+0

我认为你的问题在于你正在使用HTML生成工具来生成'text/plain',看起来像'text/html'很糟糕,但它不是HTML,不应该被当作HTML 。 –

+0

@ muistooshort,我将代码包装在'text/template'标签中,但Razor助手在生成代码时并不完全在意。 Underscore不会像我希望的那样处理'<'。我只是想找一种方法让Razor和Underscore.js一起工作。 – Brandon

回答

0

,如果你想使用从代码隐藏商提供的颜色岂不是更好地把颜色属性模型上有些凌乱那是否一定会认为?然后,你可以使用:

public class MyModel 
{ 
    public string ColorField {get;set;} //not sure whether you wanted string color or hex color here. CHange it as necessary 
    //also add whatever else you need the UI to bind to 
} 

在你的控制,当你建立模型,你会把默认值:

public ViewResult MyViewName() 
{ 
    MyModel model = new MyModel { ColorField = "blue"; // or hex color/etc.} 
    //add other initialization here 
    return View(model); 
} 

然后在您的视图

@model MyModel 

@Html.TextBoxFor(model=>model.ColorField, "color") 

它在我看来,你正在将传统的ASP.NET语法与Razor语法混合在一起,但是我没有在MVC中使用ASP.NET语法,所以我可能错了,我想从旧的一个干净的休息。

无论如何,我上面描述的方式是我总是将默认值放到我的表单字段中,并且它工作得很好。

+1

'<%= color %>'用于客户端的Underscore模板:http://underscorejs.org/#template –

+0

@anyeone,mu是正确的。我在客户端使用Backbone/Underscore.js。 '<%%'是ASP.NET语法,但在这种情况下,它与Underscore.js模板一起使用。 – Brandon

+0

对不起,我误解了这个问题。我的错! – anyeone