MVC3/C#/Razor/EF handling data from multiple partial 'create views' - c#

For registering a new customer I have several partials on my view which refer to corresponding tables in my database.
Primary keys are identity fields, that's why no IDs on the view. To insert a new customer I need to insert 3 occurrences of address(visiting, postal and contact person's), then insert a row for contract, contact_person(with using addressId from one of already inserted addresses) and finally proceed with inserting a new customer which will contain foreign keys referencing to just inserted visiting and postal addresses, contract and contact person.
Could you recommend the best/easiest way to pass the data from these partial views as objects to CustomerController and handle the objects there please?
Links to examples of handling similar situations will be also highly appreciated.
Image of my page:
http://i1345.photobucket.com/albums/p673/swell_daze/customer_registration_zps563341d0.png
Image of tables:
http://i1345.photobucket.com/albums/p673/swell_daze/tables_zpsc60b644a.png
View code:
#model CIM.Models.customer
<h2>Register new customer</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New customer registration</legend>
<fieldset class="span3">
<legend>Basic information</legend>
<div class="editor-label">
#Html.LabelFor(model => model.name, "Name")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.name)
#Html.ValidationMessageFor(model => model.name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.groupId, "Customer group")
</div>
<div class="editor-field">
#Html.DropDownList("groupId", String.Empty)
#Html.ValidationMessageFor(model => model.groupId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.status, "Status")
</div>
<div class="editor-field">
#Html.DropDownList("status")
#Html.ValidationMessageFor(model => model.status)
</div>
</fieldset>
<fieldset class="span3">
<legend>Visiting address</legend>
<div>
#{
Html.RenderPartial("AddressPartial");
}
</div>
</fieldset>
<fieldset style="width:270px">
<legend>Postal address</legend>
<div>
#{
Html.RenderPartial("AddressPartial");
}
</div>
</fieldset>
<fieldset class="span3">
<legend>Contract</legend>
<div>
#{
Html.RenderPartial("ContractPartial");
}
</div>
</fieldset>
<fieldset class="span3" style="width:540px">
<legend>Contact person</legend>
<div>
#{
Html.RenderPartial("ContactPersonPartial");
}
</div>
<p>
<input type="submit" class="btn btn-success" value="Submit" style="margin-right:1em"/>
#Html.ActionLink("Cancel", "Index", "Customer", new {#class="btn btn-danger", #type="button"})
</p>
</fieldset>
</fieldset>
}

you can wrap your view data in a viewmodel, then when you submit your data it will be mapped to your viewmodel, something like this:
Create a viewmodel:
public class MyViewModel
{
public string name { get; set; }
public string someprop1 { get; set; }
public string someprop2 { get; set; }
public MyAddress visitingaddress { get; set; }
public MyAddress postaladdress { get; set; }
public MyContactAddress contactaddress { get; set; }
}
public class MyAddress
{
public string town { get; set; }
public string street { get; set; }
public string housenumber { get; set; }
public string postalcode { get; set; }
}
public class MyContactAddress : MyAddress
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string phonenumber { get; set; }
}
Create your view just like you have done but by using your viewmodel instead of the model you are using now (CIM.Models.customer), and then in your partials, for example in the postal address partial view do something like this:
.......
#Html.EditorFor(x => x.postaladdress.town)
......
Create your controller actions by using your viewmodel:
public ActionResult Index()
{
MyViewModel vm = new MyViewModel();
//doing something here....
return View(vm);
}
[HttpPost]
public ActionResult Index(MyViewModel vm)
{
//save your data, here your viewmodel will be correctly filled
return View(vm);
}
hope this helps

Related

C# - ASP.NET MVC Get data from form to controller, I get an empty object

i can't seem to find the answer online...
I have a form where people can add persons. However the person I receive from the post request is empty.
My personModel has a few properties , Naam, Leeftijd and Hobbie.
My Create view has a form made with #Html.LabelFor.
Model:
public class PersoonModel
{
public string Naam { get; private set; }
public int Leeftijd { get; private set; }
public string Hobbie { get; private set; }
public PersoonModel(string naam,int leeftijd, string hobbie )
{
Naam = naam;
Leeftijd = leeftijd;
Hobbie = hobbie;
}
public PersoonModel()
{
}
}
View:
#using (Html.BeginForm("Create","Dashboard",FormMethod.Post))
{
<fieldset>
<legend>Persoon</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Naam)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Naam)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Leeftijd)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Leeftijd)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Hobbie)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Hobbie)
</div>
<input type="submit" value="Create new Person"/>
</fieldset>
Controller:
[HttpGet]
public ActionResult Create()
{
PersoonModel persoonModel = new PersoonModel();
return View(persoonModel);
}
[HttpPost]
public ActionResult Create(PersoonModel Persoon)
{
personen.Add(Persoon);
return Redirect("/Dashboard");
}
I can't seem to get the layout good on stackoverflow, but I hope you understand it
The persoonmodel Persoon(in my Controller) is empty
The problem is that your setters are private and MVC model binder cannot fill-in the private values:
public class PersoonModel
{
// remove private before set
public string Naam { get; set; }
public int Leeftijd { get; set; }
public string Hobbie { get; set; }
// more code...
}
I don't understand why you are using all that code in your model.
I also took the liberty to change the variables to english.
Just use this
The Model
public class PersonModel
{
public string Name { get; set; }
public int PID { get; set; }
public string Hobbie { get; set; }
}
The View
// path to your personModel
#ApplicationName.ModelFolder.PersonModel
#using (Html.BeginForm("Create","Dashboard",FormMethod.Post))
{
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PID)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Hobbie)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Hobbie)
</div>
<input type="submit" value="Create new Person"/>
</fieldset>
}
and the controller
[HttpGet]
public ActionResult Create()
{
PersonModel personModel = new PersonModel();
return View(personModel);
}
[HttpPost]
public ActionResult Create(PersonModel model)
{
personen.Add(model);
return Redirect("/Dashboard");
}
This should get the values on the post function if you debug it.

Razor checkboxes for list of models

User Model
public class UserModel
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
public IEnumerable<UserPets> UserPets { get; set; }
}
User Pets Model
public class UserPetsModel
{
public PetModel Pet{ get; set; }
public bool UserHasPet { get; set; }
}
Using these 2 models I am creating an edit page where a User can come in and edit which Pets they have.
To enable them to state which pets they have I am trying to use checkboxes.
Edit Page
#model Models.UserModel
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(model => model.FirstName)
#Model.FirstName
</div>
#foreach (var userPets in Model.UserPets)
{
#Model.Pet.AnimalName
<div>
#Html.CheckBoxFor(u => userPets .UserHasPet)
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
The problem I am having is when trying to map the UserModel back to the controller action. When I press the save button, everything on the UserModel is being mapped back to the controller apart from the UserPetsModels which I believe is due to the use of the foreach.
Is there another way in which I can display a checkbox for each UserPetModel without using a foreach or a for loop.
Yes there is. You should create EditorTemplate for your UserPetsModel. It will look like:
#model UserPetsModel
#Model.Pet.AnimalName
<div>
#Html.CheckBoxFor(model => model.UserHasPet)
</div>
And then you can simply do:
#Html.EditorFor(model => model.UserPets)
EditorFor will create right binding for you. Note that you should create EditorTemplate only for UserPets and it also will work for List<UserPetsModel> and IEnumarable<UserPetsModel> with the same syntax that i show.
I would suggest replace the loop with EditorTemplate. So your
#foreach (var userPets in Model.UserPets)
{
#Model.Pet.AnimalName
<div>
#Html.CheckBoxFor(u => userPets.UserHasPet)
</div>
}
would look like:
<div class="row">
#Html.EditorFor(m => m.UserPets)
</div>
And define a view in (~/Views/Shared/EditorTemplates/UserPets.cshtml) like:
#model UserPetsModel
#Html.HiddenFor(x => x.Pet.PetId)
#Html.LabelFor(x => x.UserHasPet, Model.Pet.AnimalName)
#Html.CheckBoxFor(x => x.UserHasPet)

Create Item and add images for Item in one step

I am trying to learn ASP.net by making an e-commerce site. I am trying to set up the ability to create Items and assign Images to the item being created via File Upload.
I managed to get the multiple file upload working, but only to the content/Images folder. I cant figure out out to marry this to the creation of Items so you can assign multiple images to an Item all in the creation of the item.
It would be a fair to say I dont know where to go from here and would appreciate any help.
Item Model Class: Table in the database to store each item. Is referenced from the Images Table with a 1 to many relationship.
public class Item
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ItemId { get; set; }
public int CategoryId { get; set; }
public int DesignerId { get; set; }
public int ImageId { get; set; }
[Required]
[MaxLength(250)]
public string ItemName { get; set; }
[Required]
[Range(0,9999)]
public decimal ItemPrice { get; set; }
[MaxLength(1000)]
public string ItemDescription { get; set; }
[Range(4,22)]
public int ItemSize { get; set; }
[Column("CategoryId")]
public virtual List<Category> Category { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
public virtual List<Image> Images { get; set; }
}
Image Model Class: Stores the URL for each Image in the content Directory of the site. Can have many images for each Item.
public class Image
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ImageId { get; set; }
[Required]
public string ImageURL { get; set; }
[Required]
public string ItemId { get; set; }
//Files Being Uploaded by the User
public IEnumerable<HttpPostedFileBase> Files { get; set; }
[Column("ItemId")]
public virtual List<Item> Item { get; set; }
}
Store Manager Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Item item,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
//The below successfully saves the file to the content folder when separated into the Index Action.
foreach (var f in item.Files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(f.FileName);
var path = Path.Combine(Server.MapPath("~/Content/ItemImages/"+item), fileName);
file.SaveAs(path);
}
}
// The below also works when I dont have the Above in the Action.
db.Items.Add(item);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(item);
}
Create Item View
#model Project.Models.Item
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Item</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ItemName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ItemName)
#Html.ValidationMessageFor(model => model.ItemName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ItemPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ItemPrice)
#Html.ValidationMessageFor(model => model.ItemPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ItemDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ItemDescription)
#Html.ValidationMessageFor(model => model.ItemDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ItemColour)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ItemColour)
#Html.ValidationMessageFor(model => model.ItemColour)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ItemSize)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ItemSize)
#Html.ValidationMessageFor(model => model.ItemSize)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<table>
<tr>
<td>Files</td>
<td><input type="file" name="Files" id="Files" multiple/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Upload" /></td>
</tr>
</table>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
So it looks like you're pretty close.
You just have to add the images to the item before adding it to the database.
Since you're using EF, it should be something similar to this
//in your action
//add the images to the item
item.Images.Add(new Image { ImageUrl = ... });
//you should be able to just insert the whole entity graph here
db.Items.Add(item);
db.SaveChanges();
Something like that I think is what you're looking for.
Also in your model constructor normally I think you want to initalize those lists so you don't get null reference execeptions when doing something like the above
public class Item
{
public Item()
{
this.Images = new List<Image>();
}
//...
}

Parent Child tables, adding child records for existing parent record add new parent records wrongly and then add child record

In EF I have two tables (parent is Office- child is Employee), I m adding records to Employee with reference of existing Office record but I guess because of my wrong configuration EF is behaving wearied.
Instead of using Office table's existing record, it add a new records in Office and use new record's id as a foreign key in child records and then create child records.
Here are my Models:
public class Office
{
public int OfficeId{ get; set; }
public string Name { get; set; }
public virtual IEnumerable<Employee> Employees{ get; set; }
}
public class Employee
{
public int EmployeeID{ get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
[NotMapped]
public int Age { get { return DOB.YearsFromUtcDateTillToday(); } }
[NotMapped]
public string FullName { get { return string.Concat(FirstName, ' ', LastName); } }
public virtual Office Office { get; set; }
}
View is strongly typed of Employee here is view code:
#model Employee
#{
ViewBag.Title = "AddEmployee";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm(MVC.CodeTest.AddEmployee(),FormMethod.Post)) {
#Html.ValidationSummary(true)
#Html.HiddenFor(model=>model.Office.OfficID)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DOB)
#Html.ValidationMessageFor(model => model.DOB)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.GPA)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.GPA)
#Html.ValidationMessageFor(model => model.GPA)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My Controller Actions are the following:
public virtual ActionResult AddEmployee(int officeId)
{
Employee st = new Employee();
st.Office=new Office();
st.Office.OfficeID= officeId;
return View(st);
}
[HttpPost]
public virtual ActionResult AddEmployee(Employee objEmployee)
{
bool success= classEmployeeService.AddEmployee(objEmployee);
if (success)
{
return RedirectToAction("Index",objEmployee.Office.OfficeId);
}
else
{
ModelState.AddModelError("", "Error! Business rule violation, can't repeat surname");
}
return View(objEmployee);
}
My Finding:
In first action (without HttpPost) OfficeId is correct, 1 in this case
Checking html I came to know it is correct
But When pressing Save button 2nd action with HttpPost is executed OfficeId value is wrong, it is new Office record id (18, 19 or next record)
Please guide and help me.
As i see you've an problem with your Model Design. The Employee class should has a property to represent the foreign key of OfficeID.
public class Employee
{
public int EmployeeID{ get; set; }
public int OfficeID{ get; set; } // This what you need
// ...... the rest of class properties
}
Then just assign the Office Id to this property not to the Navigation property "Office"
Employee st = new Employee();
st.OfficeID= officeId;
And never use st.Office=new Office(); because this will add this object to the DbContext StateManager as "Added" and it'll add it as new record to the Database.

HtmlPrefix for Partialview, remove the dot

I created a partial view that should display a list of user with a check box , so i can reuse this partial view in various pages.
The problem is that, i'm not able to have the correct htmlprefix the input generated
(I would like to remove the . of the prefix )
Model:
public class CircleEditViewModel
{
[Key]
public int CircleId { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
public bool IsSystem { get; set; }
public List<SimpleUserListViewModel> Users { get; set; }
public CircleEditViewModel()
{
Users = new List<SimpleUserListViewModel>();
}
}
public class SimpleUserListViewModel
{
public SimpleUserListViewModel()
{
}
public SimpleUserListViewModel(User user)
{
this.UserId = user.UserId;
FullName = user.FullName;
}
public int UserId { get; set; }
public byte[] Picture { get; set; }
public string FullName { get; set; }
public bool IsCheckedForAction { get; set; }
}
'Main view':
#model Wims.Website.ViewModels.CircleEditViewModel
<script type="text/javascript">
$(document).ready(function () {
$.validator.unobtrusive.parse('form');
});
</script>
#using (Ajax.BeginForm(Html.ViewContext.RouteData.Values["Action"].ToString(), null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SaveDone(data)" }, new { id = "editform" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Circle</legend>
#Html.Label(DateTime.Now.ToString());
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</fieldset>
#Html.Partial("~/Views/Shared/_UserList.cshtml", Model.Users,
new ViewDataDictionary(Html.ViewDataContainer.ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Users" }
})
#Html.GenerateSecureDataControls(model => model.CircleId)
<input type="submit" value="Save" />
}
Partial view:
#model List<Wims.Website.ViewModels.Shared.SimpleUserListViewModel>
#{
if (Model != null)
{
for (int i = 0; i < Model.Count; i++)
{
<div class="userDetail">
<div>
<div>
#Html.CheckBoxFor(model => model[i].IsCheckedForAction)
</div>
<div class="iconDiv">
#Html.Image("~/Content/Images/defaultUser.jpg", Model[i].FullName, null)
</div>
<div>
#Html.TextBoxFor(model => model[i].FullName)
#Html.HiddenFor(model => model[i].UserId)
</div>
</div>
</div>
<div style="clear: both"></div>
}
}
}
I am almost there, the input generated id's are
id="Users.[0].FullName
Is there any way i can remove the first dot?
I've found some solution yesterday on a blog (which i can't find anymore...) but it was for MVC3 and I couldn't make it work anyway...
Thanks for the help!
EDIT:
Maybe I should use EditorFor instead of partial view:
.NET MVC 4 Strongly typed ViewModel containing Strongly typed Model with EditorFor and EditorTemplate partial view not binding
Will check tonight
Alrighty, The EditorFor worked perfectly..
I need to read more about this.

Categories