Generate Asp.net MVC Model from the form fields dynamically - asp.net-mvc

I am building a Web Application where i am creating a dynamic form where user can create different field to make his or her own form.Then i want the application build their model dynamically based on the form fields.At the end database table will be created from that generated model and field value will be inserted as table data.Any suggestion or solution is highly appreciated.

I personally would shy away from trying to create the database table dynamically, but take an approach where you store the fields in a table, and relate them to a form object. Something like this:
public Form
{
[Key]
public int FormId {get;set;}
public string Name {get;set;}
public IList<Field> {get;set;}
}
public Field
{
[Key]
public int FieldId {get;set;}
public string FieldName {get;set;}
public string FieldValue {get;set;}
[ForeignKey("FormId")]
public Form Form {get;set;}
public int FormId {get;set;}
}
With this structure, creating a form would simply be a case of creating a Form object, and then you can just simply add as many Field objects to it as you wish. Each Field object can be named anything that you want, and would be unique to the Form it is associated to

Related

Automapper re-map only a child object to existing flattened VM

I have a parent and child domain object being mapped to a single ViewModel object. E.G.
class Parent
{
public int ID {get;set;}
public string Name {get;set;}
public Child Child {get;set;}
}
class Child
{
public int ID {get; set;}
public string Name {get; set;}
}
class ParentChildVM
{
public int ID {get;set;}
public string Name {get;set;}
public int ChildID {get;set;}
public string ChildName {get; set;}
}
The types are mapped in static configuration file and it just uses the built in naming conventions to map the properties and achieve the flattening.
I'm using this ParentChildVM with an ASP.NET MVC view that puts ID and Name in form inputs, but only displays ChildID and ChildName. Since the Child's properties are not in form fields, they are not posted back to the server upon saving and are empty in the ParentChildVM that is reconstructed from the posted values.
So I want to remap the Child domain object to my ParentChildVM to fill in the missing properties. But I don't want to map the Parent again because it would overwrite the edited values. Is there any way to map a given Child instance into my existing ParentChildVM with AutoMapper (v6.1.1.0)?
EDIT:
I guess I know I could add a mapping from Child -> ParentChildVM and then use .ForMember to tell it how to map ChildID and ChildName, but in reality there are a lot more properties so what I'm asking is: is there a way to do it and still take advantage of the naming-convention-based mapping? I.E. keep using the "Auto" part of AutoMapper.

MVC 5 possible to use only part of a model for the view?

If I have a database and I base all my models on the database (using LINQ basically to fetch/set the data). Is it possible to only use a part of those models to create my views? Say I have three columbs in a table, and I only need two for my view, can I simply use two of the three using my database model or should I create a new model to use in my views.
And if I have to create new models, any simple way to do this? I'm using Visual Studio 2015.
Thank you
It is common to create View Models to represent a slice of your domain model when putting data in a view.
For example you may have a BookViewModel and a BookEditModel. You could show and permit editing of different fields depending on the model.
class BookViewModel
{
[ReadOnly]
public string ISBN { get; set;}
[ReadOnly]
public string Title { get; set;}
[ReadOnly]
public string Author { get; set;}
}
class BookEditModel
{
[ReadOnly]
public string ISBN { get; set;}
[Validate(...)]
public string Title { get; set;}
[Validate(...)]
public string Author { get; set;}
[ReadOnly]
public DateTime LastUpdated {get;set;}
}
If you're looking into an easy way to create these view models, there is a tool called AutoMapper that allows you to easily map between domain and view models.

If you are using Entity Framework, how to do you use the EF Model classes instead of having to make custom View Models?

I am new to MVC. If one imports all of their existing tables in a database, they can created Entity Framework models. My question is, how do I actually use these models instead of having to fall back on creating custom View Models of the table data? Here is what I mean:
My understanding is that model classes that Entity Framework automatically generates should not be modified (example: a model of a Products table). Because of this, I have to create a whole new View Model of the Products table in order to be able to add things like [Display] and [Required] tags to the model so that I can have a custom name displayed to the user (e.g. "Store Products") and validation (e.g. the product name field is required).
See what I mean? Do you always have to manually create a View Model in order to get needed functionality like validation and user-understandable display names?
Side question: the models that Entity Framework automatically creates (based on your existing tables in the database) are called "Domain Models" right?
If the only reason you want to make separate view model is because you want to add data annotations then you can just use partial classes
eg: Given an EF generated class
public partial class MyClass
{
public int Id { get; set; }
public string SomeText { get; set; }
}
you can add a new file with:
[MetadataType(typeof(MyClassMetadata))]
public partial class MyClass
{
}
public class MyClassMetadata
{
[Required]
[Display(Name = "An Id")]
public int Id { get; set; }
[AllowHtml]
[Display(Name = "Some HTML text")]
public string SomeText { get; set; }
}
to decorate your EF classes.
Yes, this looks a bit clunky. There might be a neater way to do this in the newer versions.

Asp.Net MVC 3 Action Result parameters and data validation: are all primitive properties to be string?

Validating a form with Data Annotations using MVC.
Are you to define all properties of an input object parameter as string with data annotations so one can check the model state to catch errors, or should I just use the native data types for objects?
I created numerous "control function" models in bound which are identical to the View Models with the exception of Regex validators and "string" for each field.
Doing this seems to be unnecessary complexity. Just want to make sure I am on the right track, or that the double data models is something that MVC normally handles anyway.
For example:
public class Product
{ public int id {get;set;}
public string name {get;set;}
public double? retailPrice {get;set;}
[Required]
public int deptId {get;set;}
[Required]
public bool active {get;set;}
}
public class Product
{ [RegularExpression(#"^\d*$", ErrorMessage = "*")]
public string id {get;set;}
public string name {get;set;}
[RegularExpression(#"^\d*$", ErrorMessage = "*")]
public string retailPrice {get;set;}
[RegularExpression(#"^\d+$", ErrorMessage = "*")]
public string deptId {get;set;}
[RegularExpression(#"(?i)^true$|^false$", ErrorMessage = "*")]
public string active {get;set;}
}
Could just use the first as the inbound object, or use the second and convert to the first upon successful validation.
You should define your view models to have properties (or fields) with the correct data type. There is no requirement for them to be strings. If you have defined a property to be of type int and the model binder binds the request data to it, but cannot coerce the value to an int then the property will not be set and the model state will indicate that there is an error.
Some people have the concern of wanting to rerender the page and still have the user value in the textbox to allow them to correct it. If you use the built in Html helper methods, then this will be done for you as it looks to see if there is a model state error for that field and if there is, it will try and find the value from the request data and use that instead.

ASP.NET MVC 2: Mechanics behind an Order / Order Line in a edit form

In this question I am looking for links/code to handle an IList<OrderLine> in an MVC 2 edit form. Specifically I am interested in sending a complete order to the client, then posting the edited order back to an object (to persist) using:
Html.EditorFor(m => m.orderlines[i]) (where orderlines is an enumerable object)
Editing an Order that has multiple order lines (two tables, Order and OrderLine, one to many) is apparently difficult. Is there any links/examples/patterns out there to advise how to create this form that edits an entity and related entities in a single form (in C# MVC 2)?
The IList is really throwing me for a loop. Should I have it there (while still having one form to edit one order)? How could you use the server side factory to create a blank OrderLine in the form while not posting the entire form back to the server? I am hoping we don't treat the individual order lines with individual save buttons, deletes, etc. (for example, they may open an order, delete all the lines, then click cancel, which shouldn't have altered the order itself in either the repository nor the database.
Example classes:
public class ViewModel {
public Order order {get;set;} // Only one order
}
public class Order {
public int ID {get;set;} // Order Identity
public string name {get;set;}
public IList<OrderLine> orderlines {get;set;} // Order has multiple lines
}
public class OrderLine {
public int orderID {get;set;} // references Order ID above
public int orderLineID {get;set;} // Order Line identity (need?)
public Product refProduct {get;set;} // Product value object
public int quantity {get;set;} // How many we want
public double price {get;set;} // Current sale price
}
You need to understand List<>/Array/IEnumerable model binding:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Resources