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

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

Related

Spring unmodifiable View-/Display- Object

I want to display data which i am getting from my db in a view. As far as i know, in case i set my objects in the model defined as #ModelAtttibute, the user will be able to manipulate the data. For example: if my model has the attribute "firstname", the user will be able to manipulate the value by accessing the attribute over a get parameter(...?firstname=blabla)
In this case the model attribute is used for displaying data and not for processing user input and accodingly i dont want the user to overwrite values.
Has anyone any solutions/pattern for solving this problem?

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.

creating a form field populated by a relationship in Laravel 4

I am trying to build a form for a Happening. The Happening references a Places table by place_id.
e.g. happening "OktoberFest" has a place_id 123 which corresponds in table Places to München
These are the relationships declared in the models:
For model Place:
public function happenings()
{
return $this->hasMany('Happening');
}
For model Happening:
public function place()
{
return $this->belongsTo('Place');
}
model Happening has a place_id field linking it to Place.
I am also using {{Form::model($happening, array('route' => array('happenings.update', $happening->id)...}} as form opening
Problem 1: how to create a {{Form::text('......')}} that will be properly prefilled with München when editing the happening Oktoberfest ?
Problem 2: I was trying to get that field to work as an ajax autosuggest (i.e. starting to pull suggestions from the Places table as soon as 3 characters have been entered). I have checked a few implementations but they don't seem to mix correctly with Problem 1
To try and solve Problem 1, I have tried the solution here
Laravel 4 Form builder Custom Fields Macro
but I was unable to make it work.
Long question, it's my very first on stack overflow, please be patient :)
If a Happening is linked to Place via the column 'place_id' you have to supply an id to save in your model/table.
There are a couple of ways that I can think of:
make a list of availble Places in a radio of select, the name will be 'place_id', the value the id of the Place en something like title for the value.
instead of displaying radio's or a select a textfield with autocomplete is a great solution if you got a lot of places. I won't go into detail how to implement it but the general idea is to autocomplete the typed in placename and on selection of that place to put the id of that place in a hidden field named 'placed_id'
After saving the form save your model with the posted place_id
(and check that id if it's valid and existing, never trust user input )

MCV3: View to edit entity has to hold every column?

I got a silly general question...
If I generate a strongly typed view of an entity and chose "edit" as scaffolding, then the view does contain every column for that table. Changing and saving the values via setting it modifierd and call db.SaveChanges() does work in the controller. So far, so good.
But if I remove just one of that columns inside the view, then saving doesn't work anymore.
Is there a rule describing this? Is it only possible to make view with every column when wanting to save the model later on? I don't want to make 90 of 100 columns "hidden"...
PS: When editing a value in another table which is connected via Foreign Key (like customer.address.STREET) saving also does not work. Does everything of the entity ADDRESS has to be inside the view? I really don't get that.
Besides that: If I create my own ViewModel containing two entities: Do they also have to hold every column of both entities? This would be a whole bunch of traffic...
Answer is: You should not use the .Modified state. Instead using the UpdateModel method works fine without every field.

.NET MVC 3 Validation

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 :)

Resources