Is it a Bad idea to use `<%=` in a WebControl - c#

Recently I've started using <%= more often in my Web Controls. Typically I'll set String properties in the Code Behind and then spit them out onto the form.
Is this a bad idea?
eg.
Code Behind:
Properties:
public string TheTitle { get; set; }
public string TheBody { get; set; }
public ContentItem TheContent { get; set; }
public string ContentId {
get
{ return "content" + (TheContent != null) ? TheContent.Id.ToSTring() : "0"; }
}
Page_Load:
TheTitle = TheContentItem.Title;
TheBody = TheContentItem.Body;
On Page:
<div id='<%= ContentID %>'>
<h2 class='title'><%= TheTitle ?? "No Title" %></h2>
<p><%= TheBody %></p>
</div>

It is only a problem when the data is not validated.
Using .NET 4's <%: TheBody %> syntax is an effective way to encode potentially-untrusted data. In earlier versions of the framework, you can use <%= HttpUtility.HtmlEncode(TheBody) %> to the same effect.

It is bad if the data comes from an user input as your site will be vulnerable to XSS.

No it's not a problem* because it will be scoped to your control. You don't have to worry about anything conflicting in your case but if you were writing out server controls with IDs you could run into problems.
How your using it, ok (*assuming you have cleaned the data before assigning it to your variable). Just keep in mind there are times when it can be an issue with duplication of IDs, controls, scripts, etc...
Edit: Before assigning it to your varible you could use HttpUtility.HtmlEncode or if you using ASP.NET 4 you can use the <%: syntax depending on what you are outputting. This fall under the same rules as doing it an aspx, it's ok but you just need to be careful. This is also how much of ASP.NET MVC is used. The views can be literred with <%= and <%: Obviously using any type of encoding on any HTML itself would not be useful.

Related

Hash in Html.BeginForm

This is the row I'm having problems with:
<% using(Html.BeginForm("Create#result", "Report", FormMethod.Post)) { %>
Using C# 3.5 and MVC2 the form was rendered like this:
<form action="/Report.aspx/Create#result" method="post">
Now with C# 4.0 and MVC2 the form is rendered like this:
<form action="/Report.aspx/Create%23result" method="post">
This causes problems:
System.Web.HttpException (0x80004005): A public action method 'Create#result' was not found
I think the new behaviour is problematic and I don't want the hash escaped.
Where does it occur?
Can I change the behaviour?
The MVC version should be updated at some time, but I was working on another part when this behaviour started causing problems.
Update
I solved it by updating the form action using jquery on the client.
The form
<% using(Html.BeginForm("Create", "Report", FormMethod.Post, new { id = "frmReport" })) { %>
Javascript
var frmReport = $("#frmReport");
if (0 < frmReport.length) {
var action = frmReport.attr("action");
action = action + "#result";
frmReport.attr("action", action);
}
This occurs deep within a MVC class System.Web.Mvc.TagBuilder meaning that there probably isn't a lot you can do about it. I wouldn't be surprised if this code hasn't changed, but that the underlying html encoding function was modified with .NET 4 instead.
private void AppendAttributes(StringBuilder sb)
{
foreach (KeyValuePair<string, string> current in this.Attributes)
{
string key = current.Key;
if (!string.Equals(key, "id", StringComparison.Ordinal) || !string.IsNullOrEmpty(current.Value))
{
string value = HttpUtility.HtmlAttributeEncode(current.Value);
sb.Append(' ').Append(key).Append("=\"").Append(value).Append('"');
}
}
}
That said I'm surprised this was working for you in the first place, I believe some browsers (IE) don't support hashtags in form postbacks.

Syntax for using C# to create multiple HTML attributes via attributes.add

This is long-winded but should be easy for one of you knowledgable chaps to workout.
I have a DotNetNuke webpage with a dynamic login link. If you are not logged in the link will be 'login' and have the appropriate URL to a login popup. If you are logged in the link will be 'logout' and likewise have an the appropriate URL to the webpage that handles logout.
When the page determines if you are logged in or not the HTML link gets built with an attribute of : onclick="return dnnModal.show('http://blahblah.com....').
The code that does this:
loginLink.Attributes.Add(" onclick", "return " + UrlUtils.PopUpUrl(loginLink.NavigateUrl, this, PortalSettings, true, false, 200, 550));
Regardless of what the link is, the ID and Class always remain the same. My problem is that I would like to replace the login text with an image, infact a different image for login and logout. The issue here is that because the ID and Class stay the same I can't just do it via CSS as I normally would, but I have been able to style classes based on their attributes. I have tested this by finding out the output of the creation of the HTML link and styling the class based on the 'href' attribute for example:
a #dnn_dnnLogin_loginLink .LoginLink [href="http://some very very long dynamically created URL.aspx"]{ styles here }
The problem with this is the login/logout links change based on what page you are currently on.
I do know that each of the two rendered options has a uniqe attribue that I could style and that's their "Text" attribute. So quite simply how do I add this attribute to be rendered in HTML so that I can style it with CSS?
I have tried several variations such as:
loginLink.Attributes.Add(" onclick", "return " + UrlUtils.PopUpUrl(loginLink.NavigateUrl, this, PortalSettings, true, false, 200, 550) " Text", + loginLink.Text);
In the hope that what would be rendered would be something like:
onclick="return dnnModal.show('http://localhost/CPD/tabid/87/ctl/Login/Default.aspx?returnurl=%2fCPD.aspx&popUp=true',/*showReturn*/true,200,550,true,'')" Text="Login"
So I could style:
a #dnn_dnnLogin_loginLink .LoginLink [Text="Login"]{styles here}
a #dnn_dnnLogin_loginLink .LoginLink [Text="Logout"]{styles here}
But instead I get a generic error. I have tried various ways of writing the line without success, I just don't know the syntax.
Could someone point me in the right direction? I so hope I'm not barking up the wrong tree as this would be a really simple solution to my initial problem.
Thanks,
Edit - Code for the whole page if that helps?
using System;
using System.Web;
using System.Web.UI;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Modules;
namespace DotNetNuke.UI.Skins.Controls
{
public partial class Login : SkinObjectBase
{
private const string MyFileName = "Login.ascx";
public string Text { get; set; }
public string CssClass { get; set; }
public string LogoffText { get; set; }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
if (!String.IsNullOrEmpty(CssClass))
{
loginLink.CssClass = CssClass;
}
if (Request.IsAuthenticated)
{
if (!String.IsNullOrEmpty(LogoffText))
{
if (LogoffText.IndexOf("src=") != -1)
{
LogoffText = LogoffText.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath);
}
loginLink.Text = LogoffText;
}
else
{
loginLink.Text = Localization.GetString("Logout", Localization.GetResourceFile(this, MyFileName));
}
loginLink.NavigateUrl = Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "Logoff");
}
else
{
if (!String.IsNullOrEmpty(Text))
{
if (Text.IndexOf("src=") != -1)
{
Text = Text.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath);
}
loginLink.Text = Text;
}
else
{
loginLink.Text = Localization.GetString("Login", Localization.GetResourceFile(this, MyFileName));
}
string returnUrl = HttpContext.Current.Request.RawUrl;
if (returnUrl.IndexOf("?returnurl=") != -1)
{
returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl="));
}
returnUrl = HttpUtility.UrlEncode(returnUrl);
loginLink.NavigateUrl = Globals.LoginURL(returnUrl, (Request.QueryString["override"] != null));
if (PortalSettings.EnablePopUps && PortalSettings.LoginTabId == Null.NullInteger)
{
loginLink.Attributes.Add(" onclick", "return " + UrlUtils.PopUpUrl(loginLink.NavigateUrl, this, PortalSettings, true, false, 200, 550));
}
}
}
catch (Exception exc)
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
}
}
CSS classes are just designed for this purpose, and they are supported by all browsers that use CSS styling (even very old ones). You don't have to fight around with obscure selectors that are referencing some link that could change and break your styling again.
Since you said you already have a class assigned to these tags, you just want to specify an additional one. You can have more than one class assinged to a tag. See the W3C css class page for more info, in section 'Attribute Values':
Specifies one or more class names for an element. To specify multiple
classes, separate the class names with a space, e.g. . This allows you to combine several CSS classes for one
HTML element.
You can set the second class simply by appending it to the WebControl.CssClass string, separated by a space:
loginLink.CssClass = loginLink.CssClass + " login";
or
loginLink.CssClass = loginLink.CssClass + " logout";
this way you can access it via a single class selector or even the multiple class selector (only selects those tags that have both classes assigned) in your CSS style sheet:
.LoginLink.login { /* styles here */ }
.LoginLink.logout { /* styles here */ }
The text on the login/logout button is not stored in the Text="" attribute, but in the InnerHTML node. So your CSS selector would not apply. (I also think that the spacings in the selector are wrong, and that this solution would not support multilingual buttons, etc.)
Usually this type of styling would be implemented by in the Skin Editor (Admin/Skins/scroll down to section Skin Designer), where you select Skin or Container, File, Token=LOGIN, Setting=Text and LogoffText, and add a value src=path/to/a.gif. However, the skin designer seems to be broken in 6.1.x (bug report)
You might still try and have a look at the login.ascx and login.ascx.cs files in the admin\Skins directory of your DNN installation. Edit the code to assign loginLink.ImageUrl depending on Request.IsAuthenticated.

How can I not render a button in my view if a given property off my model has no value?

I'm new to web development. In my view, I want to conditionally show a button if Model.TemplateLocation (which is a string) is not null or empty. Below is the code that is rendering the button currently:
<div class="WPButton MyButton">
<%=Html.ActionLink(Model.TemplateLinkName, "DownloadTemplate", "ExternalData", new ArgsDownloadTemplate { Path = Model.TemplateLocation, FileName = Model.TemplateFileNameForDownload }, new{})%>
</div>
Can I wrap some C# code in the <% %>'s to test for Model.TemplateLocations value before I render that? I was told to look into #style = "display:none" somehow. Could that be what I need?
You can add control statements in code blocks to conditionally output HTML.
<% if (Model.SomeCondition) { %>
<div>
<ul>
<%=Html.ActionLink(Model.TemplateLinkName, "DownloadTemplate", "ExternalData", new ArgsDownloadTemplate { Path = Model.TemplateLocation, FileName = Model.TemplateFileNameForDownload }, new{})%>
</ul>
</div>
<% } %>
Incidentally, the <%= %> version of the tag is simply a shortcut for a code call to Response.Write(). So this will accomplish the exact same thing:
<% if (Model.SomeCondition) {
Response.Write("<div><ul>");
Response.Write (Html.ActionLink(Model.TemplateLinkName, "DownloadTemplate", "ExternalData", new ArgsDownloadTemplate { Path = Model.TemplateLocation, FileName = Model.TemplateFileNameForDownload }, new{}));
Response.Write("</ul></div>");
} %>
Much debate exists as to the correctness of either method. Many people hate the number of ASP tags they have to use to do the first way, many people feel the second way is incorrect for whatever reason. I find I use both when it offers simpler reading of the code.

Setting html attribute that is reserved keyword in Html.CheckBoxFor in ASP.NET MVC

I am using the HtmlHelper to create a checkbox in my view like so:
<%= Html.CheckBoxFor(model => model.SeatOnly, new { checked = "checked" })%>
However, an error is being thrown as checked is a reserved keyword. I have found a couple of people saying that you must use the 'reserved word prefix' and simply put an uderscore in front of the attribute like so:
<%= Html.CheckBoxFor(model => model.SeatOnly, new { _checked = "checked" })%>
This does not generate an error but in the generated html the attribute is actually '_checked' which means it doesn't work (if I use firebug and remove the underscore the attribute then takes effect).
Does anyone know a way around this while still using CheckBoxFor?
Thanks
<%= Html.CheckBoxFor(model => model.SeatOnly, new { #checked = "checked" })%>
You need to prefix it with an '#' :-)
Update
Just tested with the following and works. Try this ...
Model
public class MyModel
{
public bool SomeBooleanValue { get; set; }
public string Title { get; set; }
}
View (snipped to only the important bits)
<%= Html.TextBoxFor(x => x.Title) %>
<%= Html.CheckBoxFor(x => x.SomeBooleanValue, new { #checked = "checked" }) %>
I had the same problem: the "checked" attribute was always omitted in the html code. i solved the problem by passing "true" into the model. snippet looks like this:
MyModel model = new MyModel();
model.SomeBooleanValue = true;
As you connect the Checkbox with the Model the checkbox always shows the value the model has. If the value in your model is "false" the checkbox will always be unchecked.
Maybe this helps ..
Use #checked
Also occurs with the attribute class (reserved word), them use #class
I couldn't figure out a way to get the HtmlHelper to register the checked attribute so I simple used Html.CheckBox("SeatOnly", true) instead. This way the property in my view model is still being set and the checkbox is checked.
This is fine but I would still be interested in knowing why #checked doesn't work in the same way as #class.

EditorFor() and html properties

Asp.Net MVC 2.0 preview builds provide helpers like
Html.EditorFor(c => c.propertyname)
If the property name is string, the above code renders a texbox.
What if I want to pass in MaxLength and Size properties to the text box or my own css class property?
Do I need to create one template for each size and length combinations in my application? If so, that doesn't make the default templates that usable.
In MVC3, you can set width as follows:
#Html.TextBoxFor(c => c.PropertyName, new { style = "width: 500px;" })
I solved this by creating an EditorTemplate named String.ascx in my /Views/Shared/EditorTemplates folder:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
int maxLength = 100;
if (ViewData["size"] != null)
{
size = (int)ViewData["size"];
}
if (ViewData["maxLength"] != null)
{
maxLength = (int)ViewData["maxLength"];
}
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>
In my view, I use
<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>
Works like a charm for me!
None of the answers in this or any other thread on setting HTML attributes for #Html.EditorFor were much help to me. However, I did find a great answer at
Styling an #Html.EditorFor helper
I used the same approach and it worked beautifully without writing a lot of extra code. Note that the id attribute of the html output of Html.EditorFor is set. The view code
<style type="text/css">
#dob
{
width:6em;
}
</style>
#using (Html.BeginForm())
{
Enter date:
#Html.EditorFor(m => m.DateOfBirth, null, "dob", null)
}
The model property with data annotation and date formatting as "dd MMM yyyy"
[Required(ErrorMessage= "Date of birth is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DateOfBirth { get; set; }
Worked like a charm without writing a whole lot of extra code. This answer uses ASP.NET MVC 3 Razor C#.
May want to look at Kiran Chand's Blog post, he uses custom metadata on the view model such as:
[HtmlProperties(Size = 5, MaxLength = 10)]
public string Title { get; set; }
This is combined with custom templates that make use of the metadata. A clean and simple approach in my opinion but I would like to see this common use case built-in to mvc.
I'm surprised no one mentioned passing it in "additionalViewData" and reading it on the other side.
View (with line breaks, for clarity):
<%= Html.EditorFor(c => c.propertyname, new
{
htmlAttributes = new
{
#class = "myClass"
}
}
)%>
Editor template:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%= Html.TextBox("", Model, ViewData["htmlAttributes"])) %>
The problem is, your template can contain several HTML elements, so MVC won't know to which one to apply your size/class. You'll have to define it yourself.
Make your template derive from your own class called TextBoxViewModel:
public class TextBoxViewModel
{
public string Value { get; set; }
IDictionary<string, object> moreAttributes;
public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
{
// set class properties here
}
public string GetAttributesString()
{
return string.Join(" ", moreAttributes.Select(x => x.Key + "='" + x.Value + "'").ToArray()); // don't forget to encode
}
}
In the template you can do this:
<input value="<%= Model.Value %>" <%= Model.GetAttributesString() %> />
In your view you do:
<%= Html.EditorFor(x => x.StringValue) %>
or
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue, new IDictionary<string, object> { {'class', 'myclass'}, {'size', 15}}) %>
The first form will render default template for string. The second form will render the custom template.
Alternative syntax use fluent interface:
public class TextBoxViewModel
{
public string Value { get; set; }
IDictionary<string, object> moreAttributes;
public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
{
// set class properties here
moreAttributes = new Dictionary<string, object>();
}
public TextBoxViewModel Attr(string name, object value)
{
moreAttributes[name] = value;
return this;
}
}
// and in the view
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) %>
Notice that instead of doing this in the view, you may also do this in controller, or much better in the ViewModel:
public ActionResult Action()
{
// now you can Html.EditorFor(x => x.StringValue) and it will pick attributes
return View(new { StringValue = new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) });
}
Also notice that you can make base TemplateViewModel class - a common ground for all your view templates - which will contain basic support for attributes/etc.
But in general I think MVC v2 needs a better solution. It's still Beta - go ask for it ;-)
I think using CSS is the way to go. I wish I could do more with .NET coding, like in XAML, but in the browser CSS is king.
Site.css
#account-note-input {
width:1000px;
height:100px;
}
.cshtml
<div class="editor-label">
#Html.LabelFor(model => model.Note)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Note, null, "account-note-input", null)
#Html.ValidationMessageFor(model => model.Note)
</div>
Joe
As at MVC 5, if you wish to add any attributes you can simply do
#Html.EditorFor(m => m.Name, new { htmlAttributes = new { #required = "true", #anotherAttribute = "whatever" } })
Information found from this blog
I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.
#Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})
...and also validation works.
You can define attributes for your properties.
[StringLength(100)]
public string Body { get; set; }
This is known as System.ComponentModel.DataAnnotations.
If you can't find the ValidationAttribute that you need you can allways define custom attributes.
Best Regards,
Carlos
This may not be the slickest solution, but it is straightforward. You can write an extension to the HtmlHelper.EditorFor class. In that extension, you can supply an options parameter that will write the options to the ViewData for the helper. Here's some code:
First, the extension method:
public static MvcHtmlString EditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, TemplateOptions options)
{
return helper.EditorFor(expression, options.TemplateName, new
{
cssClass = options.CssClass
});
}
Next, the options object:
public class TemplateOptions
{
public string TemplateName { get; set; }
public string CssClass { get; set; }
// other properties for info you'd like to pass to your templates,
// and by using an options object, you avoid method overload bloat.
}
And finally, here's the line from the String.ascx template:
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = ViewData["cssClass"] ?? "" }) %>
Frankly, I think this is straightforward and clear to the poor soul who has to maintain your code down the road. And it is easy to extend for various other bits of info you'd like to pass to your templates. It's working well so far for me in a project where I'm trying to wrap as much as I can in a set of template to help standardize the surrounding html, a la http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-5-master-page-templates.html.
I wrote a blog entry to answer my own question
Adding html attributes support for Templates - ASP.Net MVC 2.0 Beta
In my practice I found that it is best to use EditorTemplates with only one HtmlHelper in it - TextBox that is in most cases. If I want a template for more complex html structure, I'll write a separate HtmlHelper.
Given that we can stick the whole ViewData object in place of htmlAttributes of the TextBox. In addition we can write some customization code for some of the properties of the ViewData if they need special treatment:
#model DateTime?
#*
1) applies class datepicker to the input;
2) applies additionalViewData object to the attributes of the input
3) applies property "format" to the format of the input date.
*#
#{
if (ViewData["class"] != null) { ViewData["class"] += " datepicker"; }
else { ViewData["class"] = " datepicker"; }
string format = "MM/dd/yyyy";
if (ViewData["format"] != null)
{
format = ViewData["format"].ToString();
ViewData.Remove("format");
}
}
#Html.TextBox("", (Model.HasValue ? Model.Value.ToString(format) : string.Empty), ViewData)
Below are the examples of the syntax in the view and the outputted html:
#Html.EditorFor(m => m.Date)
<input class="datepicker" data-val="true" data-val-required="&#39;Date&#39; must not be empty." id="Date" name="Date" type="text" value="01/08/2012">
#Html.EditorFor(m => m.Date, new { #class = "myClass", #format = "M/dd" })
<input class="myClass datepicker" data-val="true" data-val-required="&#39;Date&#39; must not be empty." id="Date" name="Date" type="text" value="1/08">
Because the question is for EditorFor not TextBoxFor WEFX's suggestion doesn't work.
For changing individual input boxes, you can process the output of the EditorFor method:
<%: new HtmlString(Html.EditorFor(m=>m.propertyname).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line my500pxWideClass\"")) %>
It is also possible to change ALL your EditorFors as it turns out MVC sets the class of EditorFor text boxes with .text-box, therefore you can just override this style, in your stylesheet or on the page.
.text-box {
width: 80em;
}
Additionally, you could set the style for
input[type="text"] {
width: 200px;
}
this overrides .text-box and will change all input text boxes, EditorFor or otherwise.
I also had issue with setting the width of TextBox in MVC3, while setting the Clsss attribute worked for TextArea control but not for TextBoxFor control or EditorFor control:
I tried following & that worked for me:
#Html.TextBoxFor(model => model.Title, new { Class = "textBox", style = "width:90%;" })
also in this case Validations are working perfectly.
One way you could get round it is by having delegates on the view model to handle printing out special rendering like this. I've done this for a paging class, I expose a public property on the model Func<int, string> RenderUrl to deal with it.
So define how the custom bit will be written:
Model.Paging.RenderUrl = (page) => { return string.Concat(#"/foo/", page); };
Output the view for the Paging class:
#Html.DisplayFor(m => m.Paging)
...and for the actual Paging view:
#model Paging
#if (Model.Pages > 1)
{
<ul class="paging">
#for (int page = 1; page <= Model.Pages; page++)
{
<li>#page</li>
}
</ul>
}
It could be seen as over-complicating matters but I use these pagers everywhere and couldn't stand seeing the same boilerplate code to get them rendered.
UPDATE: hm, obviously this won't work because model is passed by value so attributes are not preserved; but I leave this answer as an idea.
Another solution, I think, would be to add your own TextBox/etc helpers, that will check for your own attributes on model.
public class ViewModel
{
[MyAddAttribute("class", "myclass")]
public string StringValue { get; set; }
}
public class MyExtensions
{
public static IDictionary<string, object> GetMyAttributes(object model)
{
// kind of prototype code...
return model.GetType().GetCustomAttributes(typeof(MyAddAttribute)).OfType<MyAddAttribute>().ToDictionary(
x => x.Name, x => x.Value);
}
}
<!-- in the template -->
<%= Html.TextBox("Name", Model, MyExtensions.GetMyAttributes(Model)) %>
This one is easier but not as convinient/flexible.
This is the cleanest and most elegant/simple way to get a solution here.
Brilliant blog post and no messy overkill in writing custom extension/helper methods like a mad professor.
http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx
I really liked #tjeerdans answer which utilizes the EditorTemplate named String.ascx in the /Views/Shared/EditorTemplates folder. It seems to be the most straight-forward answer to this question. However, I wanted a template using Razor syntax. In addition, it seems that MVC3 uses the String template as a default (see the StackOverflow question "mvc display template for strings is used for integers") so you need to set the model to object rather than string. My template seems to be working so far:
#model object
#{ int size = 10; int maxLength = 100; }
#if (ViewData["size"] != null) {
Int32.TryParse((string)ViewData["size"], out size);
}
#if (ViewData["maxLength"] != null) {
Int32.TryParse((string)ViewData["maxLength"], out maxLength);
}
#Html.TextBox("", Model, new { Size = size, MaxLength = maxLength})
I solved it!!
For Razor the syntax is:
#Html.TextAreaFor(m=>m.Address, new { style="Width:174px" }) this adjusts the text area width to the width that i defined in the style parameter.
For ASPx the syntax is:
<%=Html.TextAreaFor(m => m.Description, new { cols = "20", rows = "15", style="Width:174px" })%>
this will do the trick

Categories