ASP.NET MVC 3 Data Attributes - Programmatically Set UIHint from Controller - asp.net-mvc-3

If i have a ViewModel like this:
public class SignupViewModel
{
[Required]
[DisplayName("Email:")]
public string EmailAddress { get; set; }
}
And use EditorFor to render out the form fields:
#Html.EditorFor(model => model.EmailAddress )
It will render <input type="text">. Cool.
But in this particular scenario, i have already retrieved Email from a different source, and i wish to pre-fill the form with this data, and show a label instead of a textbox (as i don't want them to change their email - don't worry about why).
I know i can use [UIHint], but can i do that programatically from the controller?
E.g:
var model = new SignupViewModel();
model.EmailAddress = GetFromMysterySource(); // How do i set a UIHint?
What's the best way to approach this? Should i use a seperate ViewModel altogether, which could mean changing my View from being strongly-typed to being dynamic, or should i not use EditorFor, or should i use a custom editor template?
Suggestions/advise would be greatly appreciated.

You can't apply an attribute at runtime. My suggestion would be to build a bit of logic into your view to control how the view renders the data. You may need to augment your model to indicate to the view which display to choose.
#if (Model.EmailAddressIsFixed)
{
#Html.DisplayFor( m => m.EmailAddress )
#Html.HiddenFor( m => m.EmailAddress ) // only if you need it to post back
}
else
{
#Html.EditorFor( m => m.EmailAddress )
}
If you are doing this in more than one place, then a custom editor template doing the same thing would probably be in order.
#Html.EditorFor( m => m.EmailAddress,
"FixedAddressTemplate",
new { Fixed = Model.EmailAddressIsFixed } )

Related

EditorTemplate for "Floats" not being called in ASP.NET MVC 3

I have a property of type "float" in my ViewModel. It's being displayed as a TextBox with a default value of "0".
I added an "EditorTemplates" folder inside the "Shared" folder & created a new "Float.cshtml" file with the following content:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue == 0 ? "" : ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line" })
However, still when I run the application, float fields are still being displayed with a default value of 0.
Thanks
UPDATE
I am just trying to see how ASP.NET reacts to custom templates, till now, the engine is not processing my custom template, something similar to:
LatLng.cshtml
#model float
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line "}) Latitude
On the ViewModel,
[UIHint("LatLng")]
public float? Latitude { get; set; }
On the View,
#Html.EditorFor(model => model.Latitude)
Nothing is changing, default template is being used.
Float is not actually a .NET type, it's a C# type. Float maps to System.Single, so you need to create a Single.cshtml and not a Float.cshtml.
You can also get around this by specifying a UIHint attribute on the model data, or by specifying the template to use in your Editor or EditorFor methods.
An easy workaround is if you just set ViewData.TemplateInfo.FormattedModelValue to return a string in the model, so you don't have to do that weird logic on the view. If you need it to post back a new value (for editing purposes), you just have to add some logic in the controller to turn the string back into a float.

Using Html.EditorFor to create a blank for for new records

Using the EditorFor templates is a really nice feature of ASP.Net MVC 3, but is it possible to get EditorFor to render an unpopulated template to allow for creation of records?
Or is there some other way to do this?
The ways in which I am trying to do this is as follows:
#Html.EditorFor(model => model)
#Html.EditorFor(x => new List<Business.ViewModel.Affiliate.Contact>())
#Html.EditorFor(new List<Business.ViewModel.Affiliate.Contact>())
#Html.EditorFor(new Business.ViewModel.Affiliate.Contact())
The first one obviously works, however the subsequent ones (which demonstrate what I am trying to do) all fail with the following error:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
The model in question is:
IEnumerable<Business.ViewModel.Affiliate.Contact>
It's the responsibility of the controller to prepare the view model that will be passed to the view. So if you need for example to initialize your view view model with 5 empty contact rows you could do this simply in your controller:
public ActionResult Index()
{
var model = new MyViewModel
{
// Add 5 empty contacts
Contacts = Enumerable.Range(1, 5).Select(x => new Contact()).ToList()
};
return View(model);
}
and in your view use the EditorFor helper as usual:
#model MyViewModel
...
#Html.EditorFor(x => x.Contacts)
This will render the corresponding editor template for each of the 5 elements we have added to the Contacts collection.
If your question doesn't involve AJAX, then I would design the ViewModel as following:
class MyList
{
public List<MyRow> Rows {get;set;}
public MyRow NewRow {get;set;}
}
Then you can easily add a blank editor bound to NewRow property. And in the controller you add the NewRow to Rows on subsequent calls.

MVC3 - 3 decimal places on type double with leading zero

I have a field for weight in Kgs (type double or use something else??).
In edit view I would like the user to enter numbers to the thousandth place.
In display view I would like the Kgs to appear like 560.250
Trying to learn MVC3 + Razor.
Willing to explore JQuery, use of regular expressions, validators, view templates, view models...
The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.
Thank you in advance for your help.
You could use data annotations on your view model:
[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Weight { get; set; }
and in your view
#Html.EditorFor(x => x.Weight)
will properly format the value in the input field.
Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):
#model double?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")
and then in your view:
#Html.EditorFor(x => x.Weight)
or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:
#Html.EditorFor(x => x.Weight, "MyFormattedDouble")
Personally I prefer the first approach which uses data annotations to control the format of the double values.
To format the number just use
#string.Format("{0:0.00}", Model.Weight);
or
#Html.DisplayFor(x => string.Format("{0:0.00}", x.Weight));
#Html.EditorFor(x => string.Format("{0:0.00}", x.Weight));
to Validate
public class Model
{
[Required]
public double Weight{ get; set; }
}
I wouldn't constrain the precision they put in, just make sure that it is a valid number using javascript. You might also constrain input to only include numbers and a period.
If the user puts in something wrong (i.e. not compatible with a double type), MVC will complain when it tries to bind to the model.
its very simple
follow this method
so you have to insert DataFormatString="{0:#,##0.000#Kg}" only on gridview

Using ASP.NET MVC 3 with Razor, what's the most effective way to add an ICollection to a Create view?

I'm using Entity Framework Code First to generated my database, so I have an object defined like the following:
public class Band
{
public int Id { get; set; }
[Required(ErrorMessage = "You must enter a name of this band.")]
public string Name { get; set; }
// ...
public virtual ICollection<Genre> Genres { get; set; }
}
Now I'm looking at a create view for this and the default scaffolding isn't adding Genres to my form, which from past experience is about what I expect.
Looking online I've found Using ASP.NET MVC v2 EditorFor and DisplayFor with IEnumerable<T> Generic types which seems to come closest to what I want, but doesn't seem to make sense with Razor and possibly MVC 3, per ASP.NET MVC 3 Custom Display Template With UIHint - For Loop Required?.
At present I've added the listing of genres to the ViewBag and then loop through that listing in my create view:
#{
List<Genre> genreList = ViewBag.Genres as List<Genre>;
}
// ...
<ul>
#for (int i = 0; i < genreList.Count; i++)
{
<li><input type="checkbox" name="Genres" id="Genre#(i.ToString())" value="#genreList[i].Name" /> #Html.Label("Genre" + i.ToString(), genreList[i].Name)</li>
}
</ul>
Outside of not yet handling cases where the user has JavaScript disabled and the checkboxes need to be re-checked, and actually updating the database with this information, it does output the genres as I'd like.
But this doesn't feel right, based on how good MVC 3 has become.
So what's the most effective way to handle this in MVC 3?
I don't send lists into my View via the ViewBag, instead I use my viewmodel to do this. For instance, I did something like this:
I have an EditorTemplate like this:
#model IceCream.ViewModels.Toppings.ToppingsViewModel
<div>
#Html.HiddenFor(x => x.Id)
#Html.TextBoxFor(x =x> x.Name, new { #readonly="readonly"})
#Html.CheckBoxFor(x => x.IsChecked)
</div>
which I put in my Views\IceCream\EditorTemplates folder. I use this to display some html for allowing the user to "check" any particular topping.
Then in my View I've got something like this:
#HtmlEditorFor(model => model.Toppings)
and that will use that result in my EditorTemplate being used for each of the toppings in the Toppings property of my viewmodel.
And then I've got a viewmodel which, among other things, includes the Toppings collection:
public IEnumerable<ToppingsViewModel> Toppings { get; set; }
Over in my controller, among other things, I retrieve the toppings (however I do that in my case) and set my viewmodel's property to that collection of toppings. In the case of an Edit, where toppings may have been selected previously, I set the IsChecked member of the TopingsViewModel and it'll set the corresponding checkboxes to checked.
Doing it this way provided the correct model binding so that when the user checked a few toppings, the underlying items in the collection reflected those selections. Worked well for me, hope it's helpful for you.

My controller viewmodel isn't been populated with my dynamic views model

Im creating an application that allows me to record recipes. Im trying to create a view that allows me to add the basics of a recipe e.g. recipe name,date of recipe, temp cooked at & ingredients used.
I am creating a view that contains some jquery to load a partial view clientside.
On post im having a few troubles trying to get the values from the partial view that has been loaded using jquery.
A cut down version of my main view looks like (I initially want 1 partial view loaded)
<div id="ingredients">
#{ Html.RenderPartial("_AddIngredient", new IngredientViewModel()); }
</div>
<script type="text/javascript">
$(document).ready(function () {
var dest = $("#ingredients");
$("#add-ingredient").click(function () {
loadPartial();
});
function loadPartial() {
$.get("/Recipe/AddIngredient", {}, function (data) { $('#ingredients').append(data); }, "html");
};
});
</script>
My partial view looks like
<div class="ingredient-name">
#Html.LabelFor(x => Model.IngredientModel.IngredientName)
#Html.TextBoxFor(x => Model.IngredientModel.IngredientName)
</div>
<div class="ingredient-measurementamount">
#Html.LabelFor(x => Model.MeasurementAmount)
#Html.TextBoxFor(x => Model.MeasurementAmount)
</div>
<div class="ingredient-measurementtype">
#Html.LabelFor(x => Model.MeasurementType)
#Html.TextBoxFor(x => Model.MeasurementType)
</div>
Controller Post
[HttpPost]
public ActionResult Create(RecipeViewModel vm,IEnumerable<string>IngredientName, IEnumerable<string> MeasurementAmount, IEnumerable<string> MeasurementType)
{
Finally my viewmodel looks like
public class IngredientViewModel
{
public RecipeModel RecipeModel { get; set; }
public IEnumerable<IngredientModel> Ingredients { get; set; }
}
My controller is pretty ugly......im using Inumerble to get the values for MeasurementAmount & MeasurementType (IngredientName always returns null), Ideally I thought on the httppost Ingredients would be populated with all of the on I would be able Ingredients populated
What do I need to do to get the values from my partial view into my controller?
Why don't you take a look at the MVC Controlstoolkit
I think they would do what you want.
Without getting in too much detail. Can you change the public ActionResult Create to use FormCollection instead of a view model? This will allow you to see what data is coming through if any. It would help if you could post it then.
Your view model gets populated by using Binding - if you haven't read about it, it might be a good idea to do that. Finally I would consider wrapping your lists or enums into a single view model.
Possible Problem
The problem could lay with the fact that the new Partial you just rendered isn't correctly binded with your ViewModel that you post later on.
If you inspect the elements with firebug then the elements in the Partial should be named/Id'ed something like this: Ingredients[x].Property1,Ingredients[x].Property2 etc.
In your situation when you add a partial they are probably just called Property1,Property2.
Possible Solution
Give your properties in your partial the correct name that corresponds with your List of Ingredients. Something like this:
#Html.TextBox("Ingredients[x].Property1","")
Of, after rendering your partial just change all the names en ID's with jquery to the correct value.
It happens because fields' names from partial view do not fit in default ModelBinder convention. You should analyze what names fields have in your partial view.
Also you should implement correct way of binding collections to MVC controller. You could find example in Phil's Haack post
Assuming RecipeViewModel is the model being supplied to the partial view, try just accepting that back in your POST controller like this:
[HttpPost]
public ActionResult Create(RecipeViewModel vm)
{
//
}
You should get the model populated with all the values supplied in the form.

Resources