I know that what I'm trying to do is bad idea, but I have specific constrains for now.
I have multiple sites, using one and the same MVC3 code base. For one of them the requirement is to hide some required fields from the form.
I know that the best approach is to modify the controller to set the defaults for these fields, but I'd like to achieve this modifying only the view for this particular site w/o changing the code.
So, how do I set a particular model property to a default value in the view? The ideal should be something like:
#Html.HiddenFor(model => model.RequiredProperty)
#model.RequiredProperty = "default"
EDIT: more explanation
So, actually this is in a sub-view, which is used by 2 different main views. I need these properties set only if one particular main view is used, and not the others.
So, I guess the setting to default need to go to that particular "main" view. Looks like I can not use HiddenFor in the sub-view, and then Html.Hidden in the main.
Is there a way to check in the sub-view which is the outer view?
If I understand correct you will have something like this:
<input value="default" id="sth" name="sth" type="hidden">
And to get it you have to write:
#Html.HiddenFor(m => m.sth, new { Value = "default" })
for Strongly-typed view.
There is a Hidden helper alongside HiddenFor which lets you set the value.
#Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
#{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>#frame.GetMethod().Name - #frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
#{Model.RequiredProperty = "default";}
#Html.HiddenFor(model => model.RequiredProperty)
How about like this
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
return HiddenFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
return htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
}
Use it like this
#Html.HiddenFor(customerId => reviewModel.CustomerId, Site.LoggedInCustomerId, null)
Related
I have a project with many large views (editable forms; think surveys of sorts). The customer, in pilot phase mind you, wants a role that can view all forms and elements, but should not be able to edit/save.
One easy fix would perhaps be to check for a Role and toggle the submit-buttons on/off. But I am hoping there is some decently easy way to transform a view from editable to readonly without entering HTML's #readonly on every element (there is well over thousand elements, ranging from anything from TextBoxFor, EditorFor to Checkbox and textareas).
The project utilizes three roles: Admin, Centre and Patient. In the controller in question I have [Authorize(Roles="Admin,Centre")], but this probably needs to go now (or I need to add Patient) since the latter needs a complete readOnly-access.
Any ideas on how to get this working, without editing every model attribute and/or every razor-editor?
Project uses mvc3, razor, jquery and jQuery-ui
Just to close this old question I'll present the way I solved it.
I had to overload "TextBoxFor", "CheckBoxFor" (etc.), adding a boolean parameter for readOnly/disabled to the end of the methods. Exmaple below:
//Overload TextBoxFor with a "disabled" parameter. For use with readonly-roles
public static IHtmlString TextBoxForRo<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
{
var attributes = new RouteValueDictionary();
if (htmlAttributes != null)
{
foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes))
{
attributes.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}
}
if (disabled)
{
attributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(expression, attributes);
}
I had to do this for every type or form-input, and obviously I had to replace a lot of calls in the views. It works though and it was the best solution I could think up.
I am trying to use output caching on an HTML Helper. However, even with the attribute set, this code block is always entered when the Helper method is called. Since the outputcache attribute won't work in this scenario, what would be the recommended way of caching "expensive" queries in Html Helpers?
[OutputCache(Duration = 60)]
public static MvcHtmlString CountryDropDownListFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object selectedValue)
{
var doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/countries.xml"));
var items = new Dictionary<string, string>();
foreach (XmlNode node in doc.SelectNodes("//country"))
{
items.Add(node.InnerText, node.InnerText);
}
return html.DropDownListFor(expression, new SelectList(items, "key", "value", selectedValue));
}
Output caching lets you store the output of an action method in memory on the Web server. For example, if the action method renders a view, the view page will be cached. This cached page is then available to the application for subsequent requests. Output caching saves your application the time and resources it would take to re-create the result of the action method.
In ASP.NET MVC, you can use the OutputCacheAttribute attribute to mark action methods whose output you want to cache. If you mark a controller with the OutputCacheAttribute attribute, the output of all action methods in the controller will be cached.
details http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.108).aspx
You use this attribure for not action method
Correct Example
[OutputCache(Duration = 50000)]
public ActionResult CountryDropDownListFor()
{
// Code
}
And in your view you can use Html.PartialAction to render one
Does anybody know a way to turn off MVC3 automatically decorating primitive types with a data-val-* attribute.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
removes the data-val-required attribute, but I can't seem to find a way to turn off primitive types eg: data-val-number
I have a lot of hidden int fields which don't required validating on a form, but because of these attributes they are getting validated, causing my app to appear frozen.
I imagine that the hidden int fields have the [Required] data annotations defined on them in the viewmodel? If so then I believe you just need to remove the data annotation to prevent the data-val-required attribute from being displayed.
I could be wrong, but I suspect you will then say that the field is required when that viewmodel is used in some other views?
If this is the case, then rather than turning off the data annotations (which is essentially a work around) then you need to define your view models correctly. Ideally, each view model should be specific for the view that it is defined (see pattern 3 of the following link). This will avoid the issues where you have fields that are required on some views and are not required on others.
I couldn't seem to find a way to turn this off, so created my own HtmlHelper as a way to get around this issue.
public static IHtmlString HiddenInputFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var memberExpression = (MemberExpression)expression.Body;
string fullID = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(memberExpression.Member.Name);
var builder = new TagBuilder("input");
builder.MergeAttribute("type", "hidden");
var value = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
builder.MergeAttribute("value", value.ToString());
string fullName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
builder.MergeAttribute("name", fullName);
builder.GenerateId(fullID);
var tag = builder.ToString(TagRenderMode.SelfClosing);
return new HtmlString(tag);
}
I've noticed that if you load a partial view from an ajax request, the validations (data-val-*) inside the partial view are not automatically added. So I finally changed my code to load from ajax the heavy form data that doesn't need validations.
You can specify data-val="false" in the HTML input which you are creating on the page, for example:
<input type="checkbox" name="foo" value="#item.foo" class="input-validation-error"
data-val="false">
I created an HtmlHelper method called DisplayListBoxFor that will need display a textual representation of the selected items in a MultiSelectList as an unordered list (UL/LI) in the browser. I have specific reasons to keep the signature between the standard ListBoxFor and my custom DisplayListBoxFor exactly the same, which means that my method needs to accept a lambda expression. I have the following code in my helpers class that is modeled off of the Html.ListBoxFor method:
public static MvcHtmlString DisplayListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
TagBuilder tag = new TagBuilder("ul");
foreach (var value in ((MultiSelectList)selectList).SelectedValues)
{
TagBuilder itemTag = new TagBuilder("li");
itemTag.SetInnerText(value.ToString());
tag.InnerHtml += itemTag.ToString();
}
return new MvcHtmlString(tag.ToString());
}
I can then call my custom method like so:
#Html.DisplayListBoxFor(x => Model.MySelectedValues, Model.MyAvailableValues)
The types I used are as follows:
Model.MySelectedValues = List<Object>
Model.MyAvailableValues = MultiSelectList
This works just fine, with the exception that the output only lists the ID value and not the name of the selected value because that is all that is stored in the MultiSelectList.SelectedValues property upon creation. I am trying to find a way in my foreach loop to match up the selected value to the value name, but since everything within the method is an anyonymous type, I can't cast it to any non-concrete values or even use an Indexer to find the id and name properties. How would I be able to get these values from the anonymous types passed to this method?
I figured out a solution to this, but I posted in a separate post where I "dumbed down" the question. See MVC Method to output unordered list from the ListBoxFor method
This is a follow on from the following question:
MVC 3 + $.ajax - response seems to be caching output from partial view
There is a detailed description of the problem over there. However, I have now managed to narrow down the problem, that seems to be with the Html.EditorFor helpers, hence the new question.
The issue:
I post data to the server using $.ajax, then return the html of the partial view that holds the input controls. The problem is that, despite passing a newly created object to the Partial Views model, the various #Html.EditorFor and #Html.DropDownListFor helpers return the OLD DATA!.
I can prove that the model has correctly passed in a new object to the helpers, by printing the value out beside the Html helper. Ie:
#Html.EditorFor(model => model.Transaction.TransactionDate)
#Model.Transaction.TransactionDate.ToString()
As the following image shows, the #Html.EditorFor is returning the wrong data:
[Note that the value beside the Comentario text box is a date time, because I was testing replacing the default values with a value that would change with each post, ie, a DateTime.]
If I replace the #Html.EditorFor for TransactionDate with a plain old #Html.TextBox():
#Html.TextBox("Transaction_TransactionDate", Model.Transaction.TransactionDate)
Then it renders the correct TransactionDate value for a new Transaction object, ie, DateTime.MinValue (01/01/0001...).
Therefore...
The problem is with the #Html.EditorFor helpers. The problem also happens with TextBoxFor and DropDownListFor.
The problem being that these helpers seem to cache the old value.
What am I doing wrong??!
EDIT:
I have just tried debugging in the custom Editor template for dates, and in there, ViewData.TemplateInfo.FormattedModelValue shows the correct value, ie, "01/01/0001". However, once it gets to Fiddler, the response is showing the old date, eg, "01/09/2011" in the image above.
As a result, I just think that there is some caching going on here, but I have none set up, so nothing makes any sense.
There is no caching involved here. It's just how HTML helper work. They first look at the ModelState when binding their values and then in the model. So if you intend to modify any of the POSTed values inside your controller action make sure you remove them from the model state first:
[HttpPost]
public virtual ActionResult AjaxCreate(Transaction transaction)
{
if (ModelState.IsValid)
{
service.InsertOrUpdate(transaction);
service.Save();
}
service.ChosenCostCentreId = transaction.IdCostCentre;
TransactionViewModel viewModel = new TransactionViewModel();
ModelState.Remove("Transaction");
viewModel.Transaction = new Transaction();
ModelState.Remove("CostCentre");
viewModel.CostCentre = service.ChosenCostCentre;
...
return PartialView("_Create", viewModel);
}
Even if you do not specify caching, it sometimes can occur. For my controllers which handle AJAX and JSON requests, I decorate them as follows:
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
This specifically declares no caching should occur.
UPDATE
Based on an answer Darin Dimitrov gave here, try adding the following line to your controller action:
ModelState.Clear();
i have never seen this but basically if you are using ajax to request this data, you need to set nochache: i am assuming you using jQuery.ajax here so will show the code:
$.ajax({
url: "somecontroller/someAction,
cache: false, // this is key to make sure JQUERY does not cache your request
success: function( data ) {
alert( data );
}
});
just a stab in the dark, i assume you have probably already covered this already. have you tried to create a new model first and then populate that new instance of the model with your data, and then send this to your view!
Finally not sure what DB server your using but have you check to see that DB results are not cached and that you are not just requesting SQL results from the DB cache... i dont use MsSQL but i hear that it has outputCaching until something is change on the DB server itself?? anyway just a few thoughts
This was unexpected behavior for me, and although I understand the reason why it's necessary to give ModelState precedence, I needed a way to remove that entry so that the value from Model is used instead.
Here are a couple methods I came up with to assist with this. The RemoveStateFor method will take a ModelStateDictionary, a Model, and an expression for the desired property, and remove it.
HiddenForModel can be used in your View to create a hidden input field using only the value from the Model, by first removing its ModelState entry. (This could easily be expanded for the other helper extension methods).
/// <summary>
/// Returns a hidden input field for the specified property. The corresponding value will first be removed from
/// the ModelState to ensure that the current Model value is shown.
/// </summary>
public static MvcHtmlString HiddenForModel<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
RemoveStateFor(helper.ViewData.ModelState, helper.ViewData.Model, expression);
return helper.HiddenFor(expression);
}
/// <summary>
/// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing
/// Model values on the server after a postback, to prevent ModelState entries from taking precedence.
/// </summary>
public static void RemoveStateFor<TModel, TProperty>(this ModelStateDictionary modelState, TModel model,
Expression<Func<TModel, TProperty>> expression)
{
var key = ExpressionHelper.GetExpressionText(expression);
modelState.Remove(key);
}
Call from a controller like this:
ModelState.RemoveStateFor(model, m => m.MySubProperty.MySubValue);
or from a view like this:
#Html.HiddenForModel(m => m.MySubProperty.MySubValue)
It uses System.Web.Mvc.ExpressionHelper to get the name of the ModelState property. This is especially useful when you have "Nested" models since the key name isn't obvious.
Make sure you're not doing this:
#Html.EditorFor(model => model.Transaction.TransactionDate.Date)
I did this, and the model never got the value back. It worked perfectly once I remove the .Date.