How to bind form with model data in MVC - asp.net-mvc-3

here i have one model. now i want to buil form using html helper . so when index action will be called then i want to populate model data by hand and send the model to view.
here is my model data but the way i want to build form not being possible just due to lack of knowledge. so if possible help me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace MvcPractise.Models
{
public class Student
{
[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "DOB require")] // datepicker will show
[Display(Name = "DOB :")]
[DataType(DataType.Date)]
public DateTime Dob { get; set; }
[Required(ErrorMessage = "State Required")] // drodown will show
[Display(Name = "State :")]
public List<State> State { get; set; }
[Required(ErrorMessage = "City Required")] // drodown will show
[Display(Name = "City :")]
public List<City> City { get; set; }
[Required(ErrorMessage = "Language known Required")] // group of checkboxes will show
[Display(Name = "Language known :")]
public List<Language> Language { get; set; }
[Required(ErrorMessage = "Sex Required")] // group of radio button will show
[Display(Name = "Sex :")]
public List<Sex> Sex { get; set; }
[Required(ErrorMessage = "Computer Course Required")] // listbox will show
[Display(Name = "Computer Course Done :")]
public List<ComputerCourse> ComputerCourse { get; set; }
}
public class State
{
public string ID { get; set; }
public string Name { get; set; }
}
public class City
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Language
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
public class ComputerCourse
{
public string ID { get; set; }
public string Type { get; set; }
}
}
1) for the first name & last name property i want to show textboxes
2) for the DOB property i want to show textbox with date picker
3) for the DOB property i want to show textbox with date picker
4) for the State/City property i want to show dropdown or combo
5) for the Language property i want to show group of checkboxes
6) for the Sex property i want to show 2 radio button for male & female
7) for the Computer Course property i want to show listbox
now write a index action method which will populate model with dummy data and generate UI.
when click on save button then model data will return back to action method called saved like
public ActionResult Save(Student s)
{
return View(s);
}
or
public ActionResult Save(StudentViewModel sv)
{
return View();
}
please help a newbie to learn things. thanks

Here is a good article about various types of model binding. It's not too long and demystifies the automatic binding and the manual way of doing it.
http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx
Also I would agree that this Question is a little too broad in scope. I'll try to help a little. You can use the same method name for the get and post request (The one that loads the empty page is the get, and when you fill out the form you will "post" the form data back to the post method). You will want to specify which one is using http 'get' and which one is using 'post' and you can do so with by decorating your method with an attribute like this.
[HttpGet]
public ActionResult Create()//leave it empty youre about to make it
{
var model = new ObjectType();
return view(model); // pass the new model ( empty object ) to your view;
}
[HttpPost]
public ActionResult Create(ObjectType theObject){
//MVC will try to populate the values of properties
//of theObject if they match the names on your form elements
//save it in your database
}

Related

How to bind form with complex model data in MVC

i am learning mvc.here i have one model. now i want to build form using html helper . so when index action will be called then i want to populate model data by hand and send the model to view. here is my model data but the way i want to build form not being possible just due to lack of knowledge. so if possible help me
namespace MvcPractise.Models
{
public class Student
{
[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "DOB require")] // datepicker will show
[Display(Name = "DOB :")]
[DataType(DataType.Date)]
public DateTime Dob { get; set; }
[Required(ErrorMessage = "State Required")] // drodown will show
[Display(Name = "State :")]
public List<State> State { get; set; }
[Required(ErrorMessage = "City Required")] // drodown will show
[Display(Name = "City :")]
public List<City> City { get; set; }
[Required(ErrorMessage = "Language known Required")] // group of checkboxes will show
[Display(Name = "Language known :")]
public List<Language> Language { get; set; }
[Required(ErrorMessage = "Sex Required")] // group of radio button will show
[Display(Name = "Sex :")]
public List<Sex> Sex { get; set; }
[Required(ErrorMessage = "Computer Course Required")] // listbox will show
[Display(Name = "Computer Course Done :")]
public List<ComputerCourse> ComputerCourse { get; set; }
}
public class State
{
public string ID { get; set; }
public string Name { get; set; }
}
public class City
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Language
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
public class ComputerCourse
{
public string ID { get; set; }
public string Type { get; set; }
}
}
1) for the first name & last name property i want to show textboxes
2) for the DOB property i want to show textbox with date picker
3) for the DOB property i want to show textbox with date picker
4) for the State/City property i want to show dropdown or combo
5) for the Language property i want to show group of checkboxes
6) for the Sex property i want to show 2 radio button for male & female
7) for the Computer Course property i want to show listbox
now write a index action method which will populate model with dummy data and generate UI. when click on save button then model data will return back to action method called saved like
public ActionResult Save(Student s)
{
return View(s);
}
or
public ActionResult Save(StudentViewModel sv)
{
return View();
}
guide me how to proceed. thanks
UPDATE
can i manually populate our model this way
var model = new Student()
{
FirstName = "John",
LastName = "Doe",
Dob = DateTime.Now,
State = new list<State>()
{
new state({ID="1" , Name = "test1"});
new state({ID="2" , Name = "test2"});
new state({ID="3" , Name = "test3"});
};
}
specially see this code....does it work bcoz i am not before my pc now.
State = new list<State>()
{
new state({ID="1" , Name = "test1"});
new state({ID="2" , Name = "test2"});
new state({ID="3" , Name = "test3"});
};
1) for the first name & last name property i want to show textboxes
#Html.EditorFor(x => x.FirstName)
#Html.EditorFor(x => x.LastName)
2) for the DOB property i want to show textbox with date picker
#Html.TextBoxFor(x => x.Dob, new { #class = "datePicker" })
Now pick a favorite javascript date picker library and attach it to all elements that have the date class. For example you could use jQuery UI datepicker:
$(function() {
$('.datePicker').datepicker();
});
4) for the State/City property i want to show dropdown or combo
#Html.DropDownListFor(x => x.SelectedState, new SelectList(Model.State, "ID", "Name"))
Notice the SelectedState property used here. You will need to add it to your model as a string property in order to hold the value.
5) for the Language property i want to show group of checkboxes
Start by adding a boolean property to your Language model in order to know whether it was checked or not:
public class Language
{
public string ID { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
and then:
#for (var i = 0; i < Model.Language.Count;i++)
{
#Html.HiddenFor(x => Model.Language[i].ID)
#Html.HiddenFor(x => Model.Language[i].Name)
#Html.LabelFor(x => Model.Language[i].Selected, Model.Language[i].Name)
#Html.CheckBoxFor(x => Model.Language[i].Selected)
}
6) for the Sex property i want to show 2 radio button for male & female
Then declare it as string, not some list:
public string Sex { get; set; }
and then in your view:
#Html.RadioButtonFor(x => x.Sex, "Male")
#Html.RadioButtonFor(x => x.Sex, "Female")
7) for the Computer Course property i want to show listbox
#Html.ListBoxFor(x => x.SelectedCourses, new SelectList(Model.ComputerCourse, "ID", "Type"))
now write a index action method which will populate model with dummy data and generate UI
public AcitonResult Index()
{
Student student = ... go hit your backend to get a student
return View(student);
}
Inside the view you will have a form:
#model Student
#using (Html.BeginForm())
{
... generate the desired input fields
<button type="submit">OK</button>
}
and then a POST action which will be invoked when the form is submitted:
[HttpPost]
public AcitonResult Index(Student student)
{
...
}
Also it is best practice to use a view model instead of passing to your view your domain models.

Multiple views same model[MVC 3]

I have one model and one controller for multiple views.
The model have some required fields but for a specific view i need to ignore the validation for 2 specific fields.
There is any method to ignore the validation for those 2 fields?
I am using asp.net MVC3.
Model code example:
[Required(ErrorMessage = "Campul strada este obligatoriu")]
public string Strada { get; set; }
[DisplayName("Numar strada")]
[Required(ErrorMessage = "Campul strada numar este obligatoriu")]
public string NrStrada { get; set; }
For 9/10 views that is ok but for 1 view i don't want to be requiered.
When such an issue occurs then I normally create different view models. Each with it's own validation logic. There's nothing wrong with doing it this way.
Here are examples, not relating to your code, you can adjust your code accordingly.
For example with create customer I would have a create customer view model, and for edit customer I would have a edit customer view model. Each has different sets of validation. Create customer only requirs a first name and a last name. Edit customer needs a first name, last name, and employee number of who updated the customer record. Employee number updater is not required when adding a new customer.
Here is a possible create customer view model:
public class CreateCustomerViewModel
{
[Required(ErrorMessage = "Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public string LastName { get; set; }
}
Here is a possible edit customer view model:
public class EditCustomerViewModel
{
[Required(ErrorMessage = "Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Required")]
public string UpdatedByEmployeeNumber { get; set; }
}
This is just a basic example.

update modelobject in a controller

I am trying to update user in my model object
public ActionResult AddJob(JobQueue job,HttpPostedFileBase file)
{
job.User = "itdev";
TryUpdateModel(job)
if (ModelState.IsValid)//Always returns false
{
}
}
MODEL
public class JobQueue {
[Required]
[Display(Name="JobId")]
public string JobId { get; set; }
[Required] [Display(Name = "FileName")]
public string FileName { get; set; }
[Required]
[Display(Name = "Job Run Date")]
public DateTime JobRunDate { get; set; }
[Required]
[Display(Name = "Email")]
public string Mail { get; set; }
[Required]
[Display(Name = "User")]
public string User { get; set; }
I tried using TryUpdateModel(job) and UpdateModel(job) after assigning the values.Both of these does not seem to update the model because ModelState.IsValid return false.Can someone point me in the right directions?I am using MVC3
Thanks,
Sab
I may be wrong here, but I think job.User = "itdev"; should be sufficent to update the model without using the TryUpdateModel(job) thats how we do it in our site anyway. I have never need to use any method to actually update the model itself. Just assigned values manually.
It depends on how your model is setup I guess.
You should probably post the code for your model just in case my answer isnt helpful.

ASP.Net MVC 3 AutoMapper

I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1 and also Automapper to map properties from my Objects to ViewModels and vice-versa.
I have the following class called Shift
public partial class Shift
{
public Shift()
{
this.Locations = new HashSet<ShiftLocation>();
}
public int shiftID { get; set; }
public string shiftTitle { get; set; }
public System.DateTime startDate { get; set; }
public System.DateTime endDate { get; set; }
public string shiftDetails { get; set; }
public virtual ICollection<ShiftLocation> Locations { get; set; }
}
And a ViewModel called ViewModelShift
public class ViewModelShift
{
public int shiftID { get; set; }
[DisplayName("Shift Title")]
[Required(ErrorMessage = "Please enter a Shift Title")]
public string shiftTitle { get; set; }
[DisplayName("Start Date")]
[Required(ErrorMessage = "Please select a Shift Start Date")]
public DateTime startDate { get; set; }
[DisplayName("End Date")]
[Required(ErrorMessage = "Please select a Shift End Date")]
public DateTime endDate { get; set; }
[DisplayName("Shift Details")]
[Required(ErrorMessage = "Please enter detail about the Shift")]
public string shiftDetails { get; set; }
[DisplayName("Shift location")]
[Required(ErrorMessage = "Please select a Shift Location")]
public int locationID { get; set; }
public SelectList LocationList { get; set; }
}
I then have the following code in a Controller
[HttpPost]
public ActionResult EditShift(ViewModelShift model)
{
if (ModelState.IsValid)
{
Shift shift = _shiftService.GetShiftByID(model.shiftID);
shift = Mapper.Map<ViewModelShift, Shift>(model);
}
}
Which works fine, when the variable 'shift' is first populated with Shift details, lazy loading also loads the related collection of 'Locations'.
However, once the mapping has taken place, shift.Locations then equals to 0. Is there anyway to setup AutoMapper, that it just maps over the properties in the ViewModel class to the shift without removing the collection of Locations?
Thanks as ever everyone.
Automapper has the ability to designate options for specific members of a created map.
https://github.com/AutoMapper/AutoMapper/wiki/Configuration-validation
Try this:
Mapper.CreateMap<ViewModelShift, Shift>()
.ForMember(dest => dest.Locations, opt => opt.Ignore());

Bind dropdown list from database

I have been struggling to create a Dropdown list which will display Country names from database.
The situation is:
I have a Controller "AdvertisementController", a model"AdvertisementModel" and a View "Create.cshtml".
On the view I need to create a dropdown list which will display country names from database.
I know the good thing will be to create a Viewmodel. But how shall I do that?
A bunch of code will be much appreciated. :)
I have the following code but it shows 'null reference' error.
Viewmodel:
public class CommunicationViewModel
{
public string CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
Model:
public class CreateAdModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
[DataType(DataType.MultilineText)]
public string Message { get; set; }
[Required]
[Display(Name = "Ad type")]
public string AdType { get; set; }
[Required]
[Display(Name = "Ad category")]
public string AdCategory { get; set; }
public CommunicationViewModel categories { get; set; }
}
Controller:
public ActionResult Index()
{
var query = db.AddCategory.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
}
);
var model = new CommunicationViewModel { CategoryList = query.AsEnumerable() };
return View(model);
}
Razor:
#Html.DropDownListFor(m=>m.categories.CategoryID,Model.categories.CategoryList,"--Select one--")
This may help you. Drop down for roles when adding users. very simple tutorial
http://rtur.net/blog/post/2009/06/03/Quick-and-dirty-role-management-in-ASPNET-MVC.aspx

Resources