1

I have this input element which works fine with underscore templating.

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

I want to use the Html.Helper method to generate the element instead.

I initially tried just the basic helper

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

But that gives me

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

I tried wrapping the value attribute with Html.Raw but that gives the same result, and wrapping the entire helper results in the same thing.

The entire block is wrapped in a <script type="text/template"> tag.

Why is it converting < to &lt; and how do I get it to stop?

This works, but is a little messy

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

1 回答 1

0

如果您尝试使用从代码隐藏提供的颜色,将 Color 属性放在绑定到视图的模型上不是更好吗?然后你可以使用:

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 语法混合在一起,但我没有将 ASP.NET 语法与 MVC 一起使用,所以我可能是错的,我想彻底摆脱旧的语法。

无论如何,我上面描述的方式是我总是将默认值放入我的表单字段中,并且效果很好。

于 2012-10-22T20:07:03.697 回答