.NET MVC 3 Validation - asp.net-mvc-3

I use Entity framework for creating model.
I have table hierarchy where User is my base table and I have tables Lecturer and Student which have some specific data in them. Entity framework made model that it isn't suitable so I made my middle layer called modelview where I have student table which wraps all data from both user and student tables. I have made CRUD functionality for students but I only want that admin can create student with some initial password, than admin should not have option to change student password at Edit action.
The problem is that password is required field at student Create action so I set [Required] attribute to it, but at Edit I must not have password field and my ModelState.IsValid is then always false since password field in this case isn't present and therefore is null.
I thought on adding hidden password field, but that would be very bad since someone could look at page source and see password value.
Can I somehow once this field required and another time not required?
If you have any other idea that might help please share with me.

When a user is being edited, you can put in a placeholder hidden field, with the value * (or something like that). This will satisfy the Required attribute - you just have to make sure you don't update the password when the user is edited :)

Maybe you could randomly generate a password and not have it be required at all.
Or you could remove the requred attribute and manually check if it's present at the serverside.
if (string.IsNullOrEmpty(user.Password))
ModelState.AddModelError("Password","A password is required");
To validate clientside, if you're using jquery validation: JQuery Docs

If you have separate views for Student addition and editing, an alternative solution would be:
Create a StudentViewModel class which contains all the properties required for both Student addition and editing, and
Create a StudentAdditionViewModel class (optionally derived from StudentViewModel) which includes a Password property.
You can then use StudentAdditionViewModel as the Add view's model, and StudentViewModel as the edit view's model :)

Related

How to use same model with less fields for another view in mvc5

My Question is not belonging to how to use two models on same razor view ! basically I have a user table in which i have fields like(userid,name,email,password,gender,country,department,IsActive) and my form is working fine i am able to insert update and delete i have not use EF , what i did i create the table in sql server and create the model in my model folder , in my view i have put the required field validator for all these columns and they are mandatory to input while inserting or updating.
Now I want to have another view with another controller where i do not want to show all 8 fields instead want to show just these four columns( username,email,gender,IsActive)
when i am using the same model for the other controller and view then it loads the record correctly on index view ,but when i update the required it fires validation error as all my fields are mark as required so it ask to input the rest of four fields value as well.
I have tried to remove these un-necessary fields from model in controller code before saving using Bind([Exclude]"""") but it did not work.
I have tried modelstate.remove("") this approach works fine for all fields but my password field is still throwing validation error . someone says you need to use viewmodel and in viewmodel you have to put both of your model like the full model and small model, I want to ask how my small model would be mapped to my user table (as table["tableName"] this cannot be applied to two models and pointing to same table without primary foriegn key relation .
Share example please i am confused
modelState.Remove("Password")
This remove all model values which are un-necessary but not removing the password field which gives error while updating the
You have required fields missing data or some fields are not null when being saved. What you are trying to do is completely ok. You are basically using a Virtual Model. This is what I do. In the "get", you fix your model and send it to the view. You work with it and then when you submit, you receive the model in the "post", but it is missing several REQUIRED fields. So what you need to do is, retrieve the same record from the database, update the 3 or 4 fields from the view model and then save that model that you retrieved with the new data. This is one way. (VM = view model)
1. send VM to view
2. add data in the view
3. submit
4. receive VM in POST Controller
5. get same record from DB
6. update the particular fields using the VM data
7. save the updated record to database. This is the record you retrieved in 5.
Another way is to have all the missing fields in the model but not showing them in the view. However you need to mention them in the view, otherwise they will not post. so you need to use
#Html.Hidefor( x=> x.NameOfField)
This will ensure that the field is sent back for posting. Any field with a [Required]... is required. You cannot miss it!
How will your small model be mapped to the Database. It will not. You will transfer the data from the small model to the model that is mapped in the database... with ALL the fields. Either you get the missing values from the database or from the view by using Hidefor.
example
dbmodel.Field1 = vm.field1;
dbmodel.Field2 = vm.field2;
dbmodel.Field3 = vm.field3;
I hope this helps

unique entity validation for add and edit forms

I use unique entity validation in username property of user entity,
when the user is going to be added that is ok,
but when the user is going to be edited, and username is not changed the unique entity validation impede this, because the same object already exist with that username,
how can I handle this?
PD:sorry for my poor english
Use validations groups. Link your UniqueEntity constraint to a validation group "new", then only link this group to your form when you are creating a User.

Joomla Component Dynamic Custom Field based on other Field Value

I am creating a new Joomla Component. I am able to create custom fields for the component backend forms - but I am not able to create Dynamic Custom Fields.
What I would like to do is have a field that is dynamical populated based on the value of a previous field. The easiest way to explain this is the simple country,state,city breakdown.
Field 1 = Country
Field 2 = State (Based on what the user selected as as Country in Field 1)
Field 3 = City (Based on what the user selected as State in Field 2)
The fields would of course need to be refreshed, reset as the user picks a different country etc.
The data to populate the fields would also all need to come from a database based on the previous fields value.
I am guessing this needs to be done via ajax or javascript or something? But wondering if there is an official way? Especially since there are database calls involved.
Please let me know if there is anything I can explain better..
David
I ended up just creating text fields but then validating the input to make sure the values added are correct.

Cakephp one model different form validation

I have a model name "User", their I added a validation for login. But I need to validate registration page also. Fields for both forms are different.
Can someone please tell me how to manage different form validation with 1 model.
You can validate as many fields as you want inside your User model, it does not matter in which View or in which form you input them.
So just add the fields from your registration page to the User's $validate inside your User model.
If all forms share similar fieldnames but require different validation rules you can use:
http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model
If the duplicate fields validate the same on all forms you can just add them all to the Model, it will only validate the ones present on the form.
Remember to NOT use 'required' => true, setting this key to true will make the field always required and it has to be present in the data array even if it's not on your form

ASP.NET MVC 3.0 - Maintain model state

Am new to ASP.NET MVC 3.0. Request expert's view on the below mentioned scenario.
I have a customer details page, where only Name is editable. There are 10 other customer properties that are non editable and displayed using SPAN. When user submits the page, I need to update only the Name.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
Anyone tried caching model (or viewmodel) using session id? Is it a good practice?
You are almost thinking in right direction.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
In Update Method **Load Customer again and update name Only as required and then save
**For 2 reasons
The first and most important rule is 'don't trust user data'. and
Concurrency and to avoid saving old data. See this example
Instead of using Session, I will suggest to use Hidden Field for record LastUpdateDateTime and Customer ID which will be posted back in the model to retrieve record and verify LastUpdatedtime with database record
Tipically, you should use a view model different than the database model. Having said that,in your current case the situation is very simple, submit only the name to the controller and then set the Name property of the object you get from EF with the submitted name.
Caching the view model or the model isn't your concern. The database model caching is handled by EF, your problem is mainly a lack of clear application layering. IN fact I strongly suggest to learn a bit more about the MVC pattern, basic application architecture (2-3 layering) and when and how to use a OR\M (which EF is).
use hidden inputs for other properties in your form. In that way you can get all properties binded to your EF entity and you dont need to get entity again from db.
#Html.DisplayFor(model=>model.x)
#Html.HiddenFor(model=>model.x)
or you can serialize the entity(if you use POCO entities) and set to hidden input. When you post back you should deserialize the entity.
My choice is always first one. :)

Resources