Creating and Editing related entities from a ASP.NET MVC web form - asp.net-mvc

I'm creating a ASP.NET MVC 4 web app with a database and Entity Framework 5 for a web form to maintain Document (aka Contract) entries.
Below is a sample ERD (in the form of edmx diagram with navigational properties) I have created for a DB in SQL server. For MVC web app the Model is generated from the DB with .edmx file.
Based on the Model, I have setup a form which can create and edit a Document like so:
Document Create and Edit View
This view refers to Document model class. So all the input fields using html helper (Html.TextBoxFor...,etc) are referred from Document object and its related objects (Section 1 & Section 2). The checkbox hides and shows the subform for a section with JS/jQuery. For the Edit view I use same as Create view, except it contains additional hidden ID fields to identity the records to edit from the DB.
I have added a variable length list for section item addition by following this:
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
In the partial view for the items dynamic list I use Section1Item and Section2Item as model reference.
Document Controller's Create method
So on Create the document object posted in Create(...) method contains all the attributes from the Document including the section's attributes.
If the checkbox value for Section 1 & Section 2 are false then I set the Document's Section 1 & Section 2 to null like so:
if (section1_chkbox == false) {
document.Section1 = null;
}
I have to add each item from the dynamic list into the document object like so:
foreach(Section1Item item in itemsList) {
document.Section1.Section1Items.Add(item);
}
So finally the Create method in the DocumentController adds the document in a db context and saves changes. The document and its related entities are successfully added to database tables.
Document Controller's Edit method
But when I'm editing the document with the Edit method in DocumentController there are some inconsistencies with some section1 object's ID being null for some related objects in Section1Items. For example when Section1Items are present the posted Document object (for edit) does not contain reference to Section 1 object's ID.
So it is fiddly and messy to update an existing document record as I'm having to check the ID attributes of a object. There are always errors like inconsistent principal and dependent objects in the relationship when saving or setting the object's entry state to modified.
My Question
How can I setup the View and Controller to achieve a functioning Create and Edit of a document along with its related entities as in the form's interface able? I need a efficient and correct way to use Entity Framework for this. How can I use view models for this if that would make this easier?

From what you described here I understand that there is a problem with virtual reference to Section1 from Section1Items. So in other words the problem is that entity framework model doesn't suit you display needs. You would need to render duplicated entities to map entier Document in your view. Am I right?
If that's the case I see two solutions:
like you suggested use view models to solve the problem. If you confirm the issue I can try to write example view model.
serialzie/encrypt entier Document in your view and next merge edited result with encrypted Document. You can achive that by using Mvc3Futures feature.
Serialize and encrypt your document in view:
#Html.Serialize("Document", Model, SerializationMode.EncryptedAndSigned)
And to deserialzie and decrypt you can use:
public ActionResult Edit(string id,[Deserialize(SerializationMode.EncryptedAndSigned)]Document document)

Related

Mvc How safe is viewbag?

My website is built around tabs. I have one single page with multiple partial views that display each tab.
The problem im facing now is I want to loop through files that the user has uploaded and display them in one of my partial views. This requires me to send the file list as a paramater in my action like this:
//Uploadedfiles is a function that adds the files to a list.
var files = UploadedFiles();
return View(files);
Because im only using one view to display all my partial views, i get:
The model item passed into the dictionary is of type 'Microsoft.WindowsAzure.Storage.Core.Util.CommonUtility+d__0`1[Delamapp.CloudStorageServices.UploadEntity]', but this dictionary requires a model item of type 'Delamapp.Models.LoginFolder'.
This means im required to not send a model item to my index view. Now, the only thing i can think off is adding my file list to viewbag and then display them on my view. BUT.. The files require high security. How safe is viewbag? Can you for example store sensitive login information in there? Can you think off some other way to accomplish this?
Thank you in advance
You can pass a model item to your view, but the model item you are passing doesn't match the type of model that your view uses (that's what the error message says).
So you need to do one of the following:
Modify your view to accept the model type that you are passing to it
Put the data you want to pass into the model type that your view is expecting
Create a new model type for both your data and for the view, and use that
In terms of security, I don't think using a view bag versus model binding really enters into the question of security. Both are just ways of passing data in between the controller and the view, and that all takes place within the ASP.NET process (perhaps you have ViewBag confused with Web Forms' ViewState?).

Updating Views when Model is modified

Just wondering if it is possible to update views connected to a model in ASP.NET MVC.
I am using Entity Framework database first which creates a .edmx object model for the solution.
I have created a new scaffolding model based on the model, which created:
Create.cshtml
Delete.cshtml
Details.cshtml
Edit.cshtml
Index.cshtml
If I add a property in the model, how can I update those views automatically with the new property to represent the updated model in the UI?
As explained in Changing the Database : The Official Microsoft ASP.NET Site:
To update the views you have two options - you can either re-generate the views by once again adding scaffolding for the Student class, or you can manually add the new property to your existing views. In this tutorial, you will add the scaffolding again because you have not made any customized changes to the automatically-generated views. You might consider manually adding the property when you have made changes to the views and do not want to lose those changes.
To ensure the views are re-created, first delete the Student folder under Views. Then, right-click the Controllers folder and add scaffolding for the Student model. Again, name the controller StudentController. When you click Add, you will be asked if you want to replace the existing file named StudentController. Select OK.
The views now contain the [added] MiddleName property.
Note this will apparently also overwrite your controller. Be sure to have a backup and use source control.

Concept on displaying cross-table(conjunction) data in ASP MVC

Just a rookie in .NET MVC world and still learning
I created three EF models in framework, one is clients, one is order, and items, below is the relation:
Client Order Items
PK:ID PK Order.id PK Items.ID
... FK:Client.id ...
FK:Item.id
In this case I wanna display all the client information and the item details they've bought in one table, obviously I cannot use any DBcontext here. So what should I do to combine the three table's info and output that? Create a new model on those three?
Any ideas or article are very welcomed!
I would create a ViewModel with all of the Data that you want to display. This is the model that will get populated in the controller and then it would get passed to the View.
So in the View it would use the ViewModel and wouldn't need to know about the underlying Database Model.
And in the Controller you would get the data needed and populate the ViewModel and pass that model onto the View.
Here is a page with an examples. There are plenty more out there too. http://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html

ASP.NET MVC ViewModel to Hold Lists & "Images or YouTube URL's"

I'm posting this question because I do not know the best/correct way of doing the following.
My team-mate (the designer) sent me a good looking design that includes a wizard for adding new items (for auction). The user has to fill in all the required details which include the title, description, starting price...etc AND a list of tags (up to 4 tags - chosen from the database, will use auto complete) as well as a list of up to 3 images/youtube url's (for the sake of better explanation check this image out: http://i55.tinypic.com/2v11zzr.png)
Ok so I figured out how I should do the wizard ( reference: how to make a wizard with ASP.Net MVC) but I'm not sure about how to collect the lists and the images/url's. Here's what I'm thinking:
For the images/url's, I should create a parent view model from which two sub-classes (ImageViewModel & YoutubeUrlViewModel) would inherit from and then in the controller action when I parse the post data, I would check to see the instance of the parent view model and act accordingly.
Now about the lists, I'm not sure whether I should include a List in my view model or whether I should include 4 string properties representing the tags (the same will apply to the list of images/url's).
So what's the best way of doing this?
And Haacked to the rescue: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
:)

Using a dynamic list of checkboxes in a view, how to create the model

I have an asp mvc 2 app lication where I want to display a list of check boxes that a user can select, based on a list of records in a database. To display the list my model contains a List object and the view has a foreach, and outputs Html.CheckBox for each item in the list.
Is there a way to get the model populated with the selected checkboxes, given that the model can't have specific properties for each checkbox, because the list is dynamic? Or do I have to manually iterate through the forms variables myself?
Edit: Extra details as per sabanito's comment
So in a simple view/model scenario, if my model had a property called Property1, then my view outputted a Textbox for Property1, when the form is posted via a submit button, the mvc framework will automatically populate a model with Property1 containing the text that was entered into the textbox and pass that model to the Controllers action.
Because I am dealing with a dynamic list of options the user could check, I can't write explicit boolean properties in my model and explicitly create the checkboxes in my view. Given that my list is dynamic, I'm wondering if there are ways to create my model and view so that the mvc framework is able to populate the model correctly when the form is posted.
Here's what I would do:
Are you having any issues generating the checkbox's dynamically?
If not, create a property on your ViewModel that is a:
public List<string> CheckboxResults { get; set; }
When you generate your checkbox's in the view make sure they all share the name = "CheckboxResults". When MVC see's your ViewModel as a parameter on the action method it will automatically bind and put all the "CheckboxResults" results in the List (as well as your other ViewModel properties). Now you have a dynamic List based on which checkbox's your user checked that you can send to your DomainModel or wherever.
Pretty cool stuff. Let me know if you're having issues generating the checkbox's dynamically, that's kind of a seperate issue than model binding to a list.
Use a ViewModel that reflects your view exactly, and map your domain model(s) to the viewmodel.
At first it often seems appropriate to use domain models directly in the view, for no better reason than that they're simple to use. However, as the view gets more complex over time, you end up putting a TON of conditional logic in your view, and end up with spaghetti. To alleviate this, we typically create a ViewModel that correlates 1:1 with the view.

Resources