MVC3 Set Default value for Textbox from model - asp.net-mvc-3

I have a text box created using
#Html.TextBoxFor(m => m.Model1.field1, new { #class = "login-input", #name="Name", #Value = "test" })
I want to change the default value of this textbox from "text" to a value stored in a model field. How do i set a model field as the the value attribute? Say the Name of the model to be called is Model2 and the attribute is field2. How do I set the value of the textbox to field2?

You must first write an Extension Method like this:
public class ObjectExtensions
{
public static string Item<TItem, TMember>(this TItem obj, Expression<Func<TItem, TMember>> expression)
{
if (expression.Body is MemberExpression)
{
return ((MemberExpression)(expression.Body)).Member.Name;
}
if (expression.Body is UnaryExpression)
{
return ((MemberExpression)((UnaryExpression)(expression.Body)).Operand).Member.Name;
}
if (expression.Body is ParameterExpression)
{
return expression.Body.Type.Name;
}
throw new InvalidOperationException();
}
}
It will extract the Name of property when you write sth like this: #Html.TextBoxFor(m => m.Model1.field1)
then you can use it like this:
Html.TextBoxFor(m => m.Model1.field1,
new { #class = "login-input",
#name="Name",
#value = Model.Item(m => m.Model1.field1) })
If you don't want to call m => m.Model1.field1 again, you must declare your version of TextBoxFor method which is more complicate, but If you want I can provide you the details.
This is a sample from my code base on Github:
public static class HtmlHelperExtensionForEditorForDateTime
{
public static MvcHtmlString Editor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string propname = html.ViewData.Model.Item(expression);
string incomingValue = null;
var httpCookie = html.ViewContext.RequestContext.HttpContext.Request.Cookies["lang"];
if (metadata.Model is DateTime && (httpCookie.IsNull() || httpCookie.Value == Cultures.Persian))
incomingValue = PersianCalendarUtility.ConvertToPersian(((DateTime)metadata.Model).ToShortDateString());
if (string.IsNullOrEmpty(incomingValue))
return html.TextBox(propname, null, new { #class = "datepicker TextField" });
return html.TextBox(propname, incomingValue, new { #class = "datepicker TextField"});
}
}

In your controller, set the value of field1 before passing it to the view... and that will set the value automatically. If you have the value in another field, just do:
model.field1 = model.field2;
in your controller... and that way the models have consistent data.
If you don't need/want that the default value being actually the value of the textbox, you could also use a PlaceHolder... and that way the user could see a value as a hint, but it will be not count as textbox content once you post the form.
#Html.TextBoxFor(m => m.Model1.field1, new { #class = "login-input", #name="Name", placeholder= "test" })
Remember that not all fieldnames in the HtmlAttributes need a "#"... #class is correct, but the others I don't think are needed.

You can set the default value inside your controller action just before passing the model to the view:
model.field1 = "Test"
return View(model)

Related

How can I utilise my custom DisplayTemplate with non-text fields so that it doesn't override existing values?

I've been following this guide on creating custom display attributes (specifically extra html attributes) to apply to the properties in my ViewModel. I have overridden both String and Boolean in the EditorTemplates folder. The editor template checks to see if a value has been set/the display attribute has been used - and adds the additional html attributes.
I'm getting stuck on the Boolean override when performing an edit action though. Regardless of whether or not I apply the attribute to a string, the ViewModel always maps with the correct existing data. This isn't true with any other form input type, due to the way the templates have been written by changing the type attribute inside a TextBoxFor.
I've been writing this primarily because I have been digging into knockout, and wanted an easy way to apply the data-bind attribute to strongly-typed views - if there's a better way please let me know!
Attribute Code:
public class Knockout : Attribute
{
public string DataBind { get; set; }
public string InputType { get; set; }
/*
Example:
Knockout("checked: showUploader", "checkbox")
Adds the HTML attributes data-bind="checked: showUploader" type="checkbox"
*/
public Knockout(string dataBind, string inputType)
{
this.DataBind = dataBind;
this.InputType = inputType;
}
public Dictionary<string, object> OptionalAttributes()
{
var options = new Dictionary<string, object>();
if(!string.IsNullOrWhiteSpace(DataBind))
{
options.Add("data-bind", DataBind);
}
if (!string.IsNullOrWhiteSpace(InputType))
{
options.Add("type", InputType);
}
return options;
}
}
Template Code
#using CumbriaMD.Infrastructure.ViewModels.DisplayAttributes
#{
var key = "Knockout";
}
#if (ViewData.ModelMetadata.AdditionalValues.ContainsKey(key))
{
var knockout = ViewData.ModelMetadata.AdditionalValues[key] as Knockout;
#Html.TextBoxFor(model => model, knockout.OptionalAttributes())
}
else
{
/*
When the attribute is not present, the default action is the following - which seems to
be overriding the data mapped from the database:
*/
#Html.TextBoxFor(model => model, new { type="checkbox" })
}
Found the answer nested in this beauty of a question!
My working template for boolean values now looks like:
#using CumbriaMD.Infrastructure.ViewModels.DisplayAttributes
#{
var key = "Knockout";
bool? value = null;
if(ViewData.Model != null)
{
value = Convert.ToBoolean(ViewData.Model, System.Globalization.CultureInfo.InvariantCulture);
}
}
#if (ViewData.ModelMetadata.AdditionalValues.ContainsKey(key))
{
var knockout = ViewData.ModelMetadata.AdditionalValues[key] as Knockout;
#Html.CheckBox("", value ?? false, knockout.OptionalAttributes())
}
else
{
#Html.CheckBox("", value ?? false, new { #class = "check-box" })
}

MVC3 DropDownListFor not populating selectedValue

I feel like I'm taking crazy pills. I have a dropdownlist for a view that reads from our database all of the wine producers we have. I want to set the selectedValue to a particular ID driven by the referring page. I can see it picks up the selectedValue in debug, I see the selected value populated (906 for this example), but it doesn't set the dropdownlist to the correct value when the page is rendered, it always defaults to 1 for the default value. I've tried creating the selectList in razor as opposed to my controller, but nothing works. Any help on this would be appreciated, I'm guessing it is something small.
Controller:
if (User.IsInRole("admin"))
{
if (ID != 0)
{
ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name", ID);
}
else
{
ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name");
}
}
View:
if (User.IsInRole("producereditor"))
{
<h3>#ViewBag.ProducerName</h3>
}
else
{
<div class="editor-label">
#Html.LabelFor(m => m.Wine.ProducerID, "Producer")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Wine.ProducerID, ViewBag.ProducerSelect as SelectList)
</div>
}
Tried the below but no success:
ViewBag.ProducerSelect = new SelectList(from p in db.Producers
orderby p.Name
select new { p.ProducerID, p.Name }
, "ProducerID", "Name", ID);
If you want to preselect an item, You set that value to your ProducerId property.
var yourViewModelObj=new YourViewModel;
yourViewModelObj.Wine.ProducerId=906; //or whatever value you want
return View(yourViewModelObj);
Suggestion : For better code readablity/Maintenance, Try to avoid ViewBag / ViewData and use a ViewModel to pass the data.
I would add a Property to my ViewModel to hold the Collection of Producers
public class WineViewModel
{
//Other Existing properties also
public IEnumerable<SelectListItem> Producers{ get; set; }
public string SelectedProducer { get; set; }
}
Then in yout GetAction method, you can set the value like this, If you want to set one select option as the default selected one.
public ActionResult CreateWine()
{
var vm=new WineViewModel();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.Producers= new[]
{
new SelectListItem { Value = "1", Text = "Prodcer A" },
new SelectListItem { Value = "2", Text = "Prodcer B" },
new SelectListItem { Value = "3", Text = "Prodcer C" }
};
//Now let's set the default one's value
vm.SelectedProducer = "2";
return View(vm);
}
And in your Strongly typed View,
#Html.DropDownListFor(x => x.SelectedProducer,
new SelectList(Model.Producers, "Value", "Text"), "Select Producer")
The HTML Markup generated by above code will have the HTML select with the option with value 2 as selected one.
I figured this out. I had ViewModel.wine.ProducerID elsewhere on the page in a hidden field, and that defaults to 1, so I just assigned that to passed in value, and it worked great. I knew it was something like that. Thanks!
User a ViewModel ex WineViewModel
public class WineViewModel
{
public Wine Wine { get; set; }
public SelectList PProducerList { get; set; }
public WineViewModel() { }
public WineViewModel(Wine wine)
{
this.Wine = wine;
}
}
Try the following in your controller
var model = new WineViewModel( selectwine);
model.ProjectTypeList = new SelectList( from p in db.Producers
orderby p.Name
select new { p.ID, p.Name }, "ID", "Name")
notice how I am exclusively declaring which is the ID and which is the Value in my SelectList
Then in your view do
#Html.DropDownListFor(model => model.Wine.ProducerID, Model.ProjectTypeList)

How to read property data annotation value in .NET MVC

I Just starting out w/ ASP.NET MVC 3 and I am trying to render out the following HTML for the string properties on a ViewModel on the create/edit view.
<input id="PatientID" name="PatientID" placeholder="Patient ID" type="text" value="" maxlength="30" />
Each value ties back to the property on the ViewModel, id & name are the property name, placeholder is the Display attribute, value is the value of the property, and maxlength is the StringLength attribute.
Instead of typing out the above HTML w/ the correct values for each of my string properties I thought I would try to create an EditorTemplate by the name of SingleLineTextBox and use UIHint on my string properties or pass the name of the view when I call EditFor. So far so good, except I can't figure out how to get the maxlength value off the StringLength attribute.
Here is the code I have so far:
<input id="#ViewData.ModelMetadata.PropertyName" name="#ViewData.ModelMetadata.PropertyName" placeholder="#ViewData.ModelMetadata.DisplayName" type="text" value="#ViewData.Model" maxlength="??" />
As you can see, not sure how to set maxlength value. Anyone know how?
Also, am I going about this the best way? As I said before I could just write out the plain HTML myself for each property on the page. I've looked at using TextBoxFor it wasn't setting the maxlength and was adding a bunch of validation markup to the HTML output because of the StringLength attribute which I do not want. Another option I saw was extensions/helpers off the HTML class.
A full code sample for tvanfosson's answer:
Model:
public class Product
{
public int Id { get; set; }
[MaxLength(200)]
public string Name { get; set; }
EditorTemplates\String.cshtml
#model System.String
#{
var metadata = ViewData.ModelMetadata;
var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
var attrs = prop.GetCustomAttributes(false);
var maxLength = attrs.OfType<System.ComponentModel.DataAnnotations.MaxLengthAttribute>().FirstOrDefault();
}
<input id=#Html.IdForModel()#(metadata.IsRequired ? " required" : "")#(maxLength == null ? "" : " maxlength=" + maxLength.Length) />
HTML output:
<input id=Name maxlength=200 />
Ugly but it works. Now let's abstract it and clean it up a bit. Helper class:
public static class EditorTemplateHelper
{
public static PropertyInfo GetPropertyInfo(ViewDataDictionary viewData)
{
var metadata = viewData.ModelMetadata;
var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
return prop;
}
public static object[] GetAttributes(ViewDataDictionary viewData)
{
var prop = GetPropertyInfo(viewData);
var attrs = prop.GetCustomAttributes(false);
return attrs;
}
public static string GenerateAttributeHtml(ViewDataDictionary viewData, IEnumerable<Delegate> attributeTemplates)
{
var attributeMap = attributeTemplates.ToDictionary(t => t.Method.GetParameters()[0].ParameterType, t => t);
var attrs = GetAttributes(viewData);
var htmlAttrs = attrs.Where(a => attributeMap.ContainsKey(a.GetType()))
.Select(a => attributeMap[a.GetType()].DynamicInvoke(a));
string s = String.Join(" ", htmlAttrs);
return s;
}
}
Editor Template:
#model System.String
#using System.ComponentModel.DataAnnotations;
#using Brass9.Web.Mvc.EditorTemplateHelpers;
#{
var metadata = ViewData.ModelMetadata;
var attrs = EditorTemplateHelper.GenerateAttributes(ViewData, new Delegate[] {
new Func<StringLengthAttribute, string>(len => "maxlength=" + len.MaximumLength),
new Func<MaxLengthAttribute, string>(max => "maxlength=" + max.Length)
});
if (metadata.IsRequired)
{
attrs.Add("required");
}
string attrsHtml = String.Join(" ", attrs);
}
<input type=text id=#Html.IdForModel() #attrsHtml />
So you pass in an array of Delegates, and for each entry use a Func<AttributeTypeGoesHere, string>, and then return whatever HTML string you wanted for each attribute.
This actually decouples well - you can map only the attributes you care about, you can map different sets for different parts of the same HTML, and the final usage (like #attrsHtml) doesn't harm readability of the template.
Instead of the StringLength attribute (because it's a validator attribute not a metadata provider) you can use the AdditionalMetadata attribute. Sample usage:
public class ViewModel
{
[AdditionalMetadata("maxLength", 30)]
public string Property { get; set; }
}
Basically it puts the value 30 under the key maxLength in the ViewData.ModelMetadata.AdditionalValues dictionary. So you can use it your EditorTemplate:
<input maxlength="#ViewData.ModelMetadata.AdditionalValues["maxLength"]" id="#ViewData.ModelMetadata.PropertyName" name="#ViewData.ModelMetadata.PropertyName" placeholder="#ViewData.ModelMetadata.DisplayName" type="text" value="#ViewData.Model" />
To do this you'll need to create your own HtmlHelper extension and use reflection to get at the attributes on the model property. Look at the source code at http://codeplex.com/aspnet for the existing ...For() HtmlHelper extensions. You'll need to get the PropertyInfo object for the model property using the expression that is passed in as the argument. They have several helper classes that should serve as templates for this. Once you have that, use the GetCustomAttributes method on the PropertyInfo to find the StringLength attribute and extract it's value. Since you'll be using a TagBuilder to create the input, add the length as an attribute via the TagBuilder.
...
var attribute = propInfo.GetCustomAttributes(typeof(StringLengthAttribute),false)
.OfType<StringLengthAttribute>()
.FirstOrDefault();
var length = attribute != null ? attribute.MaximumLength : 20; //provide a default
builder.Attributes.Add("maxlength",length);
...
return new MvcHtmlString( builder.ToString( TagRenderMode.SelfClosing ) );
}
See my comment on why I think this is a bad idea.
An much simpler solution is to implement a custom DataAnnotationsModelMetadataProvider like this:
internal class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
ModelMetadata modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var maxLengthAttribute = attributes.OfType<MaxLengthAttribute>().SingleOrDefault();
if (maxLengthAttribute != null)
{
modelMetadata.AdditionalValues.Add("maxLength", maxLengthAttribute.Length);
}
return modelMetadata;
}
}
In the template you can simply use:
object maxLength;
ViewData.ModelMetadata.AdditionalValues.TryGetValue("maxLength", out maxLength);
You can get the StringLength Validator from within an Editor Template, here are some examples:
https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/
What I used and tested, as a result from the article above can be seen in my answer below (tested with MVC 5, EF 6) :
ASP.NET MVC 3 - Data Annoation and Max Length/Size for Textbox Rendering
Without being specific, I've personally had some mixed results with attempts to implement some other approaches, and I don't find either claimed method particular long; however, I did think some of the other approached looked a little "prettier".
#using System.ComponentModel.DataAnnotations
#model string
#{
var htmlAttributes = ViewData["htmlAttributes"] ?? new { #class = "checkbox-inline" };
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (!attributes.ContainsKey("maxlength"))
{
var metadata = ViewData.ModelMetadata;
var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
var attrs = prop.GetCustomAttributes(false);
var maxLength = attrs.OfType<MaxLengthAttribute>().FirstOrDefault();
if (maxLength != null)
{
attributes.Add("maxlength", maxLength.Length.ToString());
}
else
{
var stringLength = attrs.OfType<StringLengthAttribute>().FirstOrDefault();
if (stringLength != null)
{
attributes.Add("maxlength", stringLength.MaximumLength.ToString());
}
}
}
}
#Html.TextBoxFor(m => m, attributes)

ASP.NET MVC - Extending TextBoxFor without re-writing the method

Is there any possible way to extend the basic html helpers (TextBoxFor, TextAreaFor, etc) using extension methods on their output, instead of just re-writing the entire methods completely? For instance, adding in ...
#Html.TextBoxFor( model => model.Name ).Identity("idName")
I know I can achieve this using the following, already..
#Html.TextBoxFor( model => model.Name, new { #id = "idName" })
But that gets clunky and frustrating to manage when you have to start adding a lot of properties. Is there any way to add extensions to these inherently without just passing in htmlAttributes for every little detail?
As #AaronShockley says, because TextBoxFor() returns an MvcHtmlString, your only option for developing a 'fluid API' style of amending the output would be to operate on the MvcHtmlStrings returned by the helper methods. A slightly different way of doing this which I think approaches what you're after would be to use a 'property builder' object, like this:
public class MvcInputBuilder
{
public int Id { get; set; }
public string Class { get; set; }
}
...and to set up extension methods like this:
public static MvcHtmlString TextBoxFor<TModel, TProp>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProp>> expression,
params Action<MvcInputBuilder>[] propertySetters)
{
MvcInputBuilder builder = new MvcInputBuilder();
foreach (var propertySetter in propertySetters)
{
propertySetter.Invoke(builder);
}
var properties = new RouteValueDictionary(builder)
.Select(kvp => kvp)
.Where(kvp => kvp.Value != null)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
return htmlHelper.TextBoxFor(expression, properties);
}
You can then do stuff like this in your View:
#this.Html.TextBoxFor(
model => model.Name,
p => p.Id = 7,
p => p.Class = "my-class")
This gives you strong typing and intellisense for input properties, which you could customise for each extension method by adding properties to an appropriate MvcInputBuilder subclass.
All of the basic html helpers return an object of type System.Web.Mvc.MvcHtmlString. You can set up extension methods for that class. Here is an example:
public static class MvcHtmlStringExtensions
{
public static MvcHtmlString If(this MvcHtmlString value, bool check)
{
if (check)
{
return value;
}
return null;
}
public static MvcHtmlString Else(this MvcHtmlString value, MvcHtmlString alternate)
{
if (value == null)
{
return alternate;
}
return value;
}
}
Then you can use these in a view like:
#Html.TextBoxFor(model => model.Name)
.If(Model.Name.StartsWith("A"))
.Else(Html.TextBoxFor(model => model.LastName)
To make extension methods that modify attributes on the rendered HTML tag, you'll have to convert the result to a string, and find and replace the value you're looking for.
using System.Text.RegularExpressions;
public static MvcHtmlString Identity(this MvcHtmlString value, string id)
{
string input = value.ToString();
string pattern = #"(?<=\bid=")[^"]*";
string newValue = Regex.Replace(input, pattern, id);
return new MvcHtmlString(newValue);
}
public static MvcHtmlString Name(this MvcHtmlString value, string id)
{
string input = value.ToString();
string pattern = #"(?<=\bname=")[^"]*";
string newValue = Regex.Replace(input, pattern, id);
return new MvcHtmlString(newValue);
}
The id and name attributes are always added by the html helpers, but if you want to work with attributes that may not be there (and you'll have to add them instead of just replacing them), you'll need to modify the code.

ViewBag property value in DropDownListFor instead of Model property value

We found strange behaviour in DropDownListFor (ASP.NET MVC3 release). It selects ViewBag property value instead of Model property value in dropdown.
Model:
public class Country {
public string Name { get; set; }
}
public class User {
public Country Country { get; set; }
}
Controller Index action:
ViewBag.CountryList = new List<Country> { /* Dropdown collection */
new Country() { Name = "Danmark" },
new Country() { Name = "Russia" } };
var user = new User();
user.Country = new Country(){Name = "Russia"}; /* User value */
ViewBag.Country = new Country() { Name = "Danmark" }; /* It affects user */
return View(user);
View:
#Html.EditorFor(user => user.Country.Name)
#Html.DropDownListFor(user => user.Country.Name,
new SelectList(ViewBag.CountryList, "Name", "Name", Model.Country), "...")
It will show text box with "Russia" value and dropdown with "Danmark" value selected instead of "Russia".
I didn't find any documentation about this behaviour. Is this behaviour normal? And why is it normal? Because it is very hard to control ViewBag and Model properties names.
This sample MVC3 project sources
I'm not so sure why this decision was made, but it was happened because MVC framework tried to use the ViewData-supplied value before using the parameter-supplied value. That's why ViewBag.Country override parameter-supplied value Model.Country.
That was how it was written in MVC framework in the private method SelectInternal.
object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));
// If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (!usedViewData) {
if (defaultValue == null) {
defaultValue = htmlHelper.ViewData.Eval(fullName);
}
}
if (defaultValue != null) {
IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };
IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
List<SelectListItem> newSelectList = new List<SelectListItem>();
foreach (SelectListItem item in selectList) {
item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
newSelectList.Add(item);
}
selectList = newSelectList;
}
This code defaultValue = htmlHelper.ViewData.Eval(fullName); tried to get the value from ViewData and if it can get the value, it will override the supplied parameter selectList with new list.
Hope it can help. Thanks.
side-node: ViewBag is just a dynamic wrapper class of ViewData.
The following line from your action method is what is confusing the code:
ViewBag.Country = new Country() { Name = "Danmark" }; /* It affects user */
That's because the html helpers look into a few different places to pick up values for the generated controls. In this case ViewData["Country"] is clashing with ModelState["Country"] Rename that property to something else and everything should work.

Resources