Asp.net MVC5 with Bootstrap EditorFor size - asp.net

I have some modifications to bring to a form which use EditorFor (and using MVC5) and I can't find the way of setting the size of the text box ...
I tried the hard way with:
#Html.EditorFor(model => model.Nom, new{#style="width:400px"})
But this did not work..
Is there an easy way?

In MVC up to version 5, EditorFor does not allow you to specify html elements in that way. It can only be used in non-editor contexts, like TextBoxFor, etc...
In MVC 5.1 they added the ability to specify html attributes in Editor templates, and you can now do this:
#Html.EditorFor(model => model, new { htmlAttributes = new { #class = "form-control" }, })

Using MVC 5 - You need to use [DataType(DataType.MultilineText)] attribute on your view model ejm:
using System.ComponentModel.DataAnnotations;
public class Requests
{
[Display(Name = "Id")]
public int RequestId { get; set; }
[DataType(DataType.MultilineText)]
public string Comments { get; set; }
}

It is not a great idea to apply css class to EditorFor template because an EditorTemplate may can have many elements in that. What you can do is to apply your css thing inside your EditorTempalte file. Checkout this answer for more details.
But if you are simply trying to render a textarea, you may simply use the TextAreaFor helper method.
#Html.TextAreaFor(model => model.Nom, new { #class = "myCustomClass" })
and your css
.myCustomClass
{
width:400px;
}
You may use !IMPORTANT if you specifically want to make sure that this css style overrides the eixsting style.
.myCustomClass
{
width:400px !IMPORTANT;
}

the same but in VB
#Html.TextBoxFor(Function(model) model.nit , New With {.class = "form-control"})

If you want to apply it to all your EditorFor, just change the max-width in your Site.css from 280px to any other value.
Example:
textarea {
/*max-width: 280px;*/
max-width: 900px;
}
This worked for me in MVC 5.1

Related

LabeFor doesn't generate display-lable class attribute

A new MVC project includes a Site.css which specifies:
/* Styles for editor and display helpers
----------------------------------------------------------*/
.display-label,
.editor-label
{
font-weight: bold;
margin: 1em 0 0 0;
}
However, when I use LabelFor(m=>m.SomeField) the generated html doesn't include the class attribute:
<label for="SomeField">Some Field</label>
I have seen other examples where people are using LabelFor and the generated html does include the class="display-label" attribute.
Is LabelFor supposed to generate this class attribute? If so, why might it be that mine is not?
I do have a custom DataAnnotationsModelMetadataProvider wired up, but it is still calling the base:
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (metadata.DisplayName == null)
metadata.DisplayName = propertyName.ToTitleCaseFromCamel();
return metadata;
}
Those css classes are only there for when you use EditorFor and DisplayFor templates. When just using LabelFor, you need to supply your own css class.
Rossis got me looking at one of my Create pages to verify his claims. As calls to EditorFor and DisplayFor also appeared to not utilize any of these css classes in my project. I started poking around the generated HTML of some of my Create/Edit pages and found the answer.
Those classes are only used in Views generated through the scaffolding options:
<div class="editor-label">
#Html.LabelFor(model => model.MeetingDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MeetingDate)
#Html.ValidationMessageFor(model => model.MeetingDate)
</div>
So you can see the generated page explicitly references the css class. It is not generated from the LabelFor Html helper call. So the class references are a result of the scaffolding, not a result of the Html helper.
Thus I have to explicitly reference them in views that I code from scratch.

How to refer to a CSS style using ASP.NET MVC?

In ASP.NET MVC I could define a textBox editor like this and give it a style.
#Html.TextBoxFor(m => m.Notes[i].Notes, new { style = "width: 500px;" });
How can I move the style to the Site.css file and just refer to it from the code above?
.myStyle {
width: 500px;
}
I tried this which compiles but doesn't seem to work:
#Html.TextBoxFor(m => m.Notes[i].Notes, "myStyle");
You want to give it a class attribute for your CSS rule to match:
#Html.TextBoxFor(m => m.Notes[i].Notes, new { #class = "myStyle" });
Note that the # in #class has no special meaning in ASP.NET MVC. It's simply there to turn class, a keyword in C#, into an identifier, so you can pass it in as a property and it'll compile.
One word of explanation. Normally if you want to add attributes, e.g. readonly, you would type:
#Html.TextBoxFor(m => m.Notes[i].Notes, new { readonly = "readonly" });
Notice there is no # in front of readonly. You have to put # in front of the class attribute, because it's a keyword in C#. If you do it in VB.NET you do not have to escape, because you define properties with a leading .:
#Html.TextBoxFor(Function(m) m.Notes[i].Notes, New With { .class = "myStyle" });

Setting initial text for validation message

I'm currently using ValidationMessageFor to locate and display any errors in my asp.net MVC3 form. To provide this on a client-side level, I'm also using JQuery's unobtrusive validation.
These methods are fantastic but they seem to be lacking one thing - an option to display an initial 'hint' when the user is in a form field, just like on Twitter's sign up form. To clarify, I'd like this to appear in the same place as the validation message.
Can anyone tell me if this functionality is available and if not, how I would go about implementing it?
Just elaborating on my comment above
The way I implemented this was by creating a "HintFor" html extension
public static MvcHtmlString HintFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression)
{
dynamic attribute = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
return MvcHtmlString.Create(attribute.Description);
}
which just displays what you set the description property on the Display attribute for that viewmodel property
[Display(Name = "Application Title", Description = "Description goes in here")]
public string Title { get; set; }
Then in my front end I formatted each form step as shown (the extra classes are because I'm using the uni-form library to format my form)
<div class="question">
#Html.LabelFor(m => m.Title, new { #class = "label" })
<div class="formHint">
#Html.HintFor(m => m.Title)
</div>
<div class="response">
#Html.TextBoxFor(m => m.Title, new { #class = "textInput", autocomplete = "off" })
</div>
<div class="sidetip">
#Html.ValidationMessageFor(m => m.Title, null, new { #class = "invalid" })
</div>
</div>
Then using a little CSS I set the "formhint" class to display none when the error message is shown
.validation-summary-valid, .field-validation-valid
{
display: none;
}
.input-validation-error + .formHint
{
display: none !important;
}
Hope this helps

TextBoxFor in EditorTemplate or DisplayTemplate

In our project we are using TextBoxFor in many places.
We would like to set the height and width of the TextBoxFor wherever we have used, for that we have done this.
<%= Html.TextBoxFor(x => x, new { #class = "TextBoxFor" } ) %>
.TextBoxFor
{
height:30px;
width:250px;
font-family:#Batang;
font-size:20px;
font-weight: bold;
}
Is it possible to to put the <%= Html.TextBoxFor("", new { #class = "TextBoxFor" } ) %> somewhere in a EditorTemplate / DisplayTemplate and in other places we just call like this
<%= Html.TextBoxFor(x => x) %>
Which means we are not specifying the css class name. So it is easy to maintain.
Any ideas. Thanks
Update, I created a static helper but it is having errors..
public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return htmlHelper.CustomTextBoxFor<TModel, TProperty>(expression, new { #class = "TextBoxFor" });
}
<%: Html.CustomTextBoxFor(m => m.Name) %>
Any ideas?
Yes, but you can also create your own Html helper, then do Html.MyTextBoxFor(...).
Check here for examples
You can download the MVC3Futures file, and it includes Templatized versions of the default templates, which you can put in your folder. You can edit these to customize the TextBoxFor used. However, you must use #Html.EditorFor(...) in your view rather than TextBoxFor(). Be aware, this will affect all uses of EditorFor in the scope where the templates are installed.
By the way, if you're using MVC3, I strongly suggest using the Razor engine rather than the WinForms engine. It's less typing, and it's more efficient, and it has features you're not going to get in WinForms.. and it discourages WinForms thinking.
If you want to apply the style for all text input fields you can modify the css style that comes with the MVC template.
input[type="text"]
{
border: 1px solid #ccc;
padding: 2px;
font-size: 1.2em;
color: #444;
}

Styling HTML helpers ASP.NET MVC

If I have an HTML helper like so:
Name:<br />
<%=Html.TextBox("txtName",20) %><br />
How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?
You can pass it into the TextBox call as a parameter.
Name:<br/>
<%= Html.TextBox("txtName", "20", new { #class = "hello" }) %>
This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the # character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.
This is how to add a class and a style on the same element...
"x" being the model passed to the view with a property of TextBoxID
#Html.TextBoxFor(x => x.TextBoxID, new { #class = "SearchBarSelect", style = "width: 20px; background-color: green;" })
I did some research and came across this article that seems to have a solution to your question.
Ajax Control Toolkit with ASP.NET MVC#
source: jimzimmerman
ARTICLE LINK
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330
QUOTE
So basically if you put the class name
TextboxWatermark on any textbox input
with the title you like to show as the
watermark like this:
<input type="text" class"TextboxWatermark" name="username" id="username" title="Must be at least 6 chars" />
or
<%= Html.TextBox("username", new { #class = "TextboxWatermark", #title = "Must be at least 6 chars" }) %>
What is nice about the second option
is that you get the added benefit of
getting the View Engine to fill out
the value of the textbox if there is
an item in ViewData of the
ViewData.Model that has a var named
'username'.
Use the htmlAttributes parameter with an anonymous type, like tihs:
<%=Html.TextBox("txtName","20", new { #class = "test"}) %>
the helper implementation
public static class LabelExtensioncs
{
public static MvcHtmlString Alarm(this HtmlHelper helper, string target, string text)
{
return MvcHtmlString.Create(string.Format("<p class='alert' style='background-color: #b8f89d;border-radius: 5px;width: 100%;'><b>{0}</b><br /><i>{1}</i></p>", target, text));
}
}
the usage in view section
#Html.Alarm("Title", "please unsure your card no is invisible in your authorized information")
the result
Theres no need to use span, because its not dynamic.
Css:
.testClass {
color: #1600d3;
}
View (Index):
#Html.TextBox("expression", "Text to show.", new { #class = "testClass" })
if you need dynamic options you can use for example:
CSS:
.test class{
background: #ffffff;
}
Controller (Index for test):
[HttpGet]
public ActionResult Index()
{
ViewBag.vbColor = "#000000";
return View();
}
View (Index):
<div>
<span>
#Html.TextBox("expression", "Text to show.", new
{ #class = "testClass", #style="color: " +
#ViewBag.vbColor })
</span>
</div>
Hope it helps.
Is it that much more work?

Resources