简体   繁体   中英

ASP.Net MVC Model Binder - Ignore Properties

I have an ASP.Net MVC5 site using Entity Framework 6.

I am using ASP.Net Identity role-based security that performs granular security checks within the page to determine if certain input fields should be visible to the user. ie

@if (User.IsInRole(MyProj.Security.Roles.ViewSocial)) {
   @Html.TextBoxFor(m=> m.SSN)
}

If the user does not have the permission, the input field is not created and thus the model binder will blank out the value of this property.

How can I work this so that it ignores these properties in the case where they are not being displayed for edit?

@Html.HiddenFor() will not work because I can't have the tags included in the client-side HTML where the values can be seen in the source.

Will I need a custom model binder in this scenario?

Yes you should do something because even HTML input can be injected through developer tools in modern browser and it will get posted to the controller and you would believe he is authorized but he is actually not.

Yes definitely you need to prevent malicious user to do so. Two option is there.

  1. you can do right logic of validating user by checking if he is authorized to do so or not.

  2. As you suggested in the code apply custom model binder for that and only set that property if he is authorized to do so.

     public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(HomePageModels)) { HttpRequestBase request = controllerContext.HttpContext.Request; string title = request.Form.Get("Title"); string day = request.Form.Get("Day"); string month = request.Form.Get("Month"); string year = request.Form.Get("Year"); if(User.IsInRole("Admin")) { string SSN = request.Form.Get("SSN"); } return new HomePageModels { Title = title, Date = day + "/" + month + "/" + year, SSN = SSN }; //// real time HomePageModels instance should be loaded from database here to avoid saving null if person is not authorized to do so } else { return base.BindModel(controllerContext, bindingContext); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM