How to make a site editable vs. readonly depending on Roles. - asp.net-mvc-3

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.

Related

How do I bypass the limitations of what MVC-CORE controllers can pass to the view?

From what I've read, I'm supposed to be using ViewModels to populate my views in MVC, rather than the model directly. This should allow me to pass not just the contents of the model, but also other information such as login state, etc. to the view instead of using ViewBag or ViewData. I've followed the tutorials and I've had both a model and a viewmodel successfully sent to the view. The original problem I had was that I needed a paginated view, which is simple to do when passing a model alone, but becomes difficult when passing a viewmodel.
With a model of
public class Instructor {
public string forename { get; set; }
public string surname { get; set; }
}
and a viewmodel of
public class InstructorVM {
public Instructor Instructors { get; set; }
public string LoggedIn { get; set; }
}
I can create a paginated list of the instructors using the pure model Instructor but I can't pass InstructorVM to the view and paginate it as there are other properties that aren't required in the pagination LoggedIn cause issues. If I pass InstructorVM.Instructors to the view, I get the pagination, but don't get the LoggedIn and as this is just the model, I may has well have passed that through directly.
An alternative that was suggested was to convert/expand the viewmodel into a list or somesuch which would produce an object like this that gets passed to the view
instructor.forename = "dave", instructor.surname = "smith", LoggedIn="Hello brian"
instructor.forename = "alan", instructor.surname = "jones", LoggedIn="Hello brian"
instructor.forename = "paul", instructor.surname = "barns", LoggedIn="Hello brian"
where the LoggedIn value is repeated in every row and then retrieved in the row using Model[0].LoggedIn
Obviously, this problem is caused because you can only pass one object back from a method, either Instructor, InstructorVM, List<InstructorVM>, etc.
I'm trying to find out the best option to give me pagination (on part of the returned object) from a viewmodel while not replicating everything else in the viewmodel.
One suggestion was to use a JavaScript framework like React/Angular to break up the page into a more MVVM way of doing things, the problem with that being that despite looking for suggestions and reading 1001 "Best JS framework" lists via Google, they all assume I have already learned all of the frameworks and can thus pick the most suitable one from the options available.
When all I want to do is show a string and a paginated list from a viewmodel on a view. At this point I don't care how, I don't care if I have to learn a JS framework or if I can do it just using MVC core, but can someone tell me how to do this thing I could do quite simply in ASP.NET? If it's "use a JS framework" which one?
Thanks
I'm not exactly sure what the difficulty is here, as pagination and using a view model aren't factors that play on one another. Pagination is all about selecting a subset of items from a data store, which happens entirely in your initial query. For example, whereas you might originally have done something like:
var widgets = db.Widgets.ToList();
Instead you would do something like:
var widgets = db.Widgets.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage).ToList();
Using a view model is just a layer on top of this, where you then just map the queried data, no matter what it is onto instances of your view model:
var widgetViewModels = widgets.Select(w => new WidgetViewModel
{
...
});
If you're using a library like PagedList or similar, this behavior may not be immediately obvious, since the default implementation depends on having access to the queryset (in order to do the skip/take logic for you). However, PagedList, for example has StaticPagedList which allows you to create an IPagedList instance with an existing dataset:
var pagedWidgets = new StaticPagedList<WidgetViewModel>(widgetViewModels, pageNumber, itemsPerPage, totalItems);
There, the only part you'd be missing is totalItems, which is going to require an additional count query on the unfiltered queryset.
If you're using a different library, there should be some sort of similar functionality available. You'll just need to confer with the documentation.

turn off data-val-* attribute on primitive types

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">

ModelBinding to a DropDownListFor with an Int64 value

In my models I have a BIGINT (long/int64) foreign key reference to LookupCategory. In the View, I have a DropDownListFor as follows:
#Html.DropDownListFor(model => model.LookupKey.LookupCategory, new SelectList(Model.LookupCategories, "ID", "Name"))
The create/edit views display fine, but upon selecting an item submitting the ModelBinder complains "The value '1' is invalid." because it is reading it in as a string rather than a long.
Is there a way to fix this without touching the model? I'd prefer not to implement ModelBinder just to solve this little issue, but if I must, I've got this drafted:
public class LookupKeyBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
if (propertyDescriptor.PropertyType == typeof(LookupKey))
{
var modelState = bindingContext.ModelState[string.Format("{0}.{1}", propertyDescriptor.Name, "LookupCategory")];
propertyDescriptor.SetValue(bindingContext.Model, long.Parse(modelState.Value.AttemptedValue));
modelState.Errors.Clear();
return;
}
}
}
It's arranged like that because I want access to the ModelState, not have to know the form field names (which could change between views). So I get the long value properly, but the problem is that the DefaultModelBinder already did its work and instead of long, I need the actual LookupCategory (whose ID is the long value). I can't figure out how to use the default model binder again to use its default behavior for finding the LookupCategory from the database. Anyway, this is a lot of trickery for something that seems like it should be simple!
As I suspected, examining the model and LookupKey classes helped resolve the issue. I have had several experiences like that, where a second look at the class showed I was not using the correct model property.
When you changed your DropDownListFor to use model.LookupKey.LookupCategory.ID, that synced up with the correct property, and viola!
Congrats on spotting the problem.

MVC 3 - Html.EditorFor seems to cache old values after $.ajax call

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.

How to set a hidden value in Razor

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)

Resources