Twitter Feed Popout byInfofru

How to redirect to default login page from action

I have been using Authorize attribute heavily to manage user authorizations, but at times just Authorize attribute is not enough. For an instance, I want user to access the Edit page of any entity which he created. In other words I don’t want him to edit records created by other users.

We cannot do this using Authorize only because it is design to limit access to an action regardless of what data is being passed to it. Thus, in this case you can maintain CreatedUser field in the record table and check on the Action if the logged in user is authorize to do this edit. Here is the code for that.

 

if (myrecord.OwnerId != User.Identity.Name) {

return new HttpUnauthorizedResult();

}

 

You can return HttpStatusCodeResult(403) too but that will only display the default access denied page of IIS, which is not we want and this is where “HttpUnauthorizedResult” comes handy.

Disable validation on field for specific view

Consider a case when you have single model which is bind to multiple views. For example, UserInforma

Consider a case when you have single model which is bind to multiple views. For example, UserInformation model bind to “Create” and “Edit” view. Now in “Create” view, I want to “Password” field as required but at the same time I want it to be optional on “Edit” view.

It means, In “Edit” view, If user provides “Password” then change it otherwise don’t update the “Password” field.

This is why it is important to create ViewModels, which gives you freedom to have different fields, validations etc for every view.

Now to achieve this goal in the given scenario, we need to make two tweaks.

 

Client Side

To disable client side validation, we need to disable it by force.

@Html.EditorFor(model => model.Password, new { htmlAttributes = new {  @data_val = "false" , @class = "form-control"} })

Notice the @data_val= “false”. It will disable the validation on this field.

 

Server Side (In Action)

When the model is validated on the post action, ModelState.IsValid will always return false because password is not provided. Here we have to provide the current password to the model and Re-validate the model.

var userObj = db.Users_Info.Where(a => a.Id == users_Info.Id).FirstOrDefault();

if (String.IsNullOrEmpty(users_Info.Password))
{
    users_Info.Password = userObj.Password;
}

ModelState.Clear();
TryValidateModel(users_Info);

Let me explain, first we retrieve current information saved in the database which we are using later to assign to current model if password is not provided. The last two lines actually reset the ModelState to return updated result on ModelState.IsValid.

Angry Coding Angry smile Angry smile Angry smile