Create View with Multiple Models and Forms with Validation - MVC 5 - c#

How can I create a view that has multiple models that need validation and also has multiple forms to submit all within the same view?
I have the solution below. As I was typing it up I was able to figure it out, so hopefully it will help someone else. If others have a better approach or comments, please feel free to post!

I have a view that contains a ViewModel, which combines 2 models. Here is the ViewModel, along with the other classes:
public class PlayerFormViewModel
{
public PlayerFormEnglish PlayerFormEnglish { get; set; }
public PlayerFormSpanish PlayerFormSpanish { get; set; }
}
public class PlayerFormEnglish : PlayerFormInformation { }
public class PlayerFormSpanish : PlayerFormInformation { }
public class PlayerFormInformation
{
[Required(ErrorMessage = "First name is a required field.")]
[Display(Name = "First name")]
public string FirstName { get; set; }
// Used as a dropdown in the view
[Display(Name = "Gender")]
public IEnumerable<SelectListItem> Gender{ get; set; }
}
My main view contains the ViewModel and 2 forms:
#model Namespace.Models.PlayerFormViewModel
#using (Html.BeginForm("PlayerTest", "Profile"))
{
#Html.AntiForgeryToken()
<h3>English</h3>
#Html.LabelFor(m => m.PlayerFormEnglish.FirstName)
#Html.TextBoxFor(m => m.PlayerFormEnglish.FirstName)
#Html.ValidationMessageFor(m => m.PlayerFormEnglish.FirstName)
#Html.LabelFor(m => m.PlayerFormEnglish.Gender)
#Html.DropDownListFor(m => m.PlayerFormEnglish.Gender, new SelectList(Model.PlayerFormEnglish.Gender, "Value", "Text"))
<button type="submit" class="btn btn-default" name="ButtonType" value="SaveEnglishForm">Save</button>
}
#using (Html.BeginForm("PlayerTest", "Profile"))
{
#Html.AntiForgeryToken()
<h3>Spanish</h3>
#Html.LabelFor(m => m.PlayerFormSpanish.FirstName)
#Html.TextBoxFor(m => m.PlayerFormSpanish.FirstName)
#Html.ValidationMessageFor(m => m.PlayerFormSpanish.FirstName)
#Html.LabelFor(m => m.PlayerFormSpanish.Gender)
#Html.DropDownListFor(m => m.PlayerFormSpanish.Gender, new SelectList(Model.PlayerFormEnglish.Gender, "Value", "Text"))
<button type="submit" class="btn btn-default" name="ButtonType" value="SaveSpanishForm">Save</button>
}
When the page first loads, I pre-populate the fields like this:
[HttpGet]
public ActionResult PlayerTest()
{
PlayerFormViewModel model = new PlayerFormViewModel();
model.PlayerFormEnglish = new PlayerFormEnglish();
model.PlayerFormSpanish = new PlayerFormSpanish();
model.PlayerFormEnglish.FirstName = "Brad";
List<SomeObject> genderList = GetDataForDropdown();
model.PlayerFormEnglish.Gender = ConvertData(genderList);
model.PlayerFormSpanish.Gender = ConvertData(genderList);
return View(model);
}
Finally, I validate and update the saved form when a user clicks the save button:
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult PlayerTest(PlayerFormViewModel model, string ButtonType)
{
if (ButtonType.Equals("SaveEnglishForm"))
{
if (ModelState.IsValid)
{
return RedirectToAction("SuccessfulSave", "Profile");
}
model.PlayerFormSpanish = new PlayerFormSpanish();
}
else
{
if (ModelState.IsValid)
{
return RedirectToAction("SuccessfulSave", "Profile");
}
model.PlayerFormEnglish = new PlayerFormEnglish();
}
// I can repopulate the fields here just as before
model.PlayerFormEnglish.FirstName = "Brad";
List<SomeObject> genderList = GetDataForDropdown();
model.PlayerFormEnglish.Gender = ConvertData(genderList);
model.PlayerFormSpanish.Gender = ConvertData(genderList);
// Return model which will mark the required fields in the UI
return View(model);
}
Hope this helps!

Related

Checkboxlist MVC Partial

I have the following view model code:
public class TestCheckboxlistParentModel
{
public TestCheckboxlistParentModel()
{
CBL = new TestCheckboxlistModel();
}
public TestCheckboxlistModel CBL { get; set; }
}
public class TestCheckboxlistModel
{
public string TextField { get; set; }
public IList<string> SelectedFruits { get; set; }
public IList<SelectListItem> AvailableFruits { get; set; }
public TestCheckboxlistModel()
{
SelectedFruits = new List<string>();
AvailableFruits = new List<SelectListItem>();
}
}
controller:
public ActionResult TestCheckboxlist()
{
var model = new TestCheckboxlistParentModel
{
CBL = new TestCheckboxlistModel()
{
AvailableFruits = GetFruits()
}
};
return View(model);
}
[HttpPost]
public ActionResult TestCheckboxlist(TestCheckboxlistParentModel model)
{
if (ModelState.IsValid)
{
// Save data to database, and redirect to Success page.
return RedirectToAction("Success");
}
//model.AvailableFruits = GetFruits();
return View(model);
}
public ActionResult Success()
{
return View();
}
private IList<SelectListItem> GetFruits()
{
return new List<SelectListItem>
{
new SelectListItem {Text = "Apple", Value = "1"},
new SelectListItem {Text = "Pear", Value = "2"},
new SelectListItem {Text = "Banana", Value = "3"},
new SelectListItem {Text = "Orange", Value = "4"},
};
}
partial view:
#model Web.ViewModels.TestCheckboxlistModel
<div class="form-group">
#Html.LabelFor(model => model.TextField)
<div class="col-md-10">
#Html.EditorFor(model => model.TextField)
</div>
</div>
#foreach (var item in Model.AvailableFruits)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="#Html.IdFor(p=>p.SelectedFruits)"
value="#item.Value" /> #item.Text
</label>
</div>
}
view:
#model Web.ViewModels.TestCheckboxlistParentModel
#{
ViewBag.Title = "TestCheckboxlist";
Layout = "~/Views/Shared/_LayoutApplicationDriver.cshtml";
}
#using (Html.BeginForm())
{
#Html.Partial("TestPartialCheckboxlist", Model.CBL, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "CBL" } })
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
}
Problem is SelectedFruits always does not have any elements in post method. The same code work correctly, if I don't use nested Partial view. Property TextField works fine with Partial
PS. It's not a dublicate of How to make Check Box List in ASP.Net MVC question. That question is a base of my answer. In my case, I need to have checkboxlist in partial view, where it does not work!
You use of name="#Html.IdFor(p => p.SelectedFruits)" generates name="CBL_SelectedFruits", but in order to bind to your model, you would need name="CBL.SelectedFruits" (note the . dot, not _ underscore) which you could generate using
name="#Html.NameFor(p => p.SelectedFruits)"
However there are other issues with your code. Your not strongly binding to your model, you get no validation, your generating a IList<SelectListItem> for property AvailableFruits when you don't need it (it could be just IList<string> AvailableFruits, and most importantly, if you return the view, all the checkboxes the user checked are lost (all checkboxes will be unchecked).
Change your view models so that you can strongly bind to your properties
public class FruitVM
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class ParentVM
{
public string TextField { get; set; }
public List<FruitVM> Fruits { get; set; }
}
and in the GET method
ParentVM model = new ParentVM
{
Fruits = new List<FruitVM>{
new FruitVM{ Name = "Apple" },
new FruitVM{ Name = "Pear" },
....
}
};
return View(model);
and create an EditorTemplate for FruitVM - in /Views/Shared/EditorTemplates/FruitVM.cshtml
#model FruitVM
#Html.CheckBoxFor(m => m.IsSelected)
#Html.LabelFor(m => m.IsSelected, Model.Name)
and in the view
#Html.ParentVM
....
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.TextField)
#Html.EditorFor(m => m.TextField)
#Html.EditorFor(m => m.Fruits)
<input type="Submit" value="Save" />
}
The EditorFor() method will generate the correct html for each item in your collection.
Then in the POST method, you can get the selected items with
[HttpPost]
public ActionResult TestCheckboxlist(ParentVM model)
{
....
List<string> selectedFruits = model.Fruits.Where(x => x.IsSelected);

Insert succeeds but the inserted value shows NULL in the back end ms sql database

I have a simple mvc5 code first application, It has a ms SQL database in the back-end and and a form in the front-end.
While I insert into database via the front end form, it does not generate any error, everything seems OK but when i check the back end database table, then all values in the newly inserted row are showing as NULL.
This is my code for model:
public class students
{
public int Id { get; set; }
[Display(Name = "Name")]
public string st_name { get; set; }
[Display(Name = "Father's Name")]
public string st_father_name { get; set; }
public string st_contact { get; set; }
}
This is the View Model class:
public class AddStudentViewModel
{
public students stdntss { get; set; }
}
This is the controller:
public ActionResult Index()
{
var std = _context.stdnts;
if (std==null)
{
return Content("Nothing Found");
}
return View(std);
}
public ActionResult AddStudent()
{
return View();
}
[HttpPost]
public ActionResult Insert(students st)
{
_context.stdnts.Add(st);
_context.SaveChanges();
return RedirectToAction("Index","Students");
}
And finally this is the view:
#model school2.ViewModels.AddStudentViewModel
#{
ViewBag.Title = "AddStudent";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New student's registration form</h2>
#using (Html.BeginForm("Insert","Students"))
{
<div class="form-group">
#Html.LabelFor(m=> m.stdntss.st_name)
#Html.TextBoxFor(m=> m.stdntss.st_name, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.stdntss.st_father_name)
#Html.TextBoxFor(m => m.stdntss.st_father_name, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.stdntss.st_contact)
#Html.TextBoxFor(m => m.stdntss.st_contact, new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Save</button>
}
Kindly assist me if anyone has any clue?
One way to solve this is to change the POST method to accept the same model as the view.
try changing
public ActionResult Insert(students st)
{
_context.stdnts.Add(st);
_context.SaveChanges();
return RedirectToAction("Index","Students");
}
to
public ActionResult Insert(AddStudentViewModel st)
{
_context.stdnts.Add(st.stdntss );
_context.SaveChanges();
return RedirectToAction("Index","Students");
}
or changing the model of the form to simply be student.
I think that change #Html.TextBoxFor(model=> model.stdntss.st_name, new { #class="form-control"}). because call Model, #model school2.ViewModels.AddStudentViewModel . Variable default Model.

Currency conversion api web service

I am a new to MVC and still learning! I am trying to create a very basic App in my web which allows users to convert money value according to their preference. I made the web APi and was successful to call the service to my forms. However, in my controller I managed to get the currencies (names) to the index view, but cannot post the form back once entering a value in the text box to generate the partial view! What am I doing wrong in my codes?!
Currency Controller
namespace MVC_ATM.Controllers
{
public class CurrencyController : Controller
{
[HttpGet]
// GET: Currency
public ActionResult Index()
{
CurrenciesClient Cur = new CurrenciesClient();
var listCurrency = Cur.findAll();
SelectList list = new SelectList(listCurrency,"Id", "CurrencyName");
ViewBag.listCurrencies = list;
return View();
}
[HttpPost]
public ActionResult Index(Currencies cur)
{
if (!ModelState.IsValid)
{
string errors = string.Join("<br />", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
return new ContentResult { Content = errors };
var rate = Convert.ToDecimal(cur.ConversionRate);
if (cur.CurrencyName == cur.CurrencyName)
{
ModelState.AddModelError("CurrencyCountry", "Can't make the conversion for the same value");
}
else if (cur.CurrencyName != cur.CurrencyName)
{
foreach (var currency in cur.CurrencyName)
{
ViewBag.Theresult = rate * cur.Value;
}
return PartialView("_CurrencyValue");
}
}
return View();
}
}
}
Currencies Model
namespace Project.Model
{
public class Currencies
{
public int Id { get; set; }
public string CurrencyName { get; set; }
public string CurrencyCountry {get; set;}
public decimal Value { get; set; }
public string ConversionRate { get; set; }
}
}
Index View
#model Project.Model.Currencies
#{
ViewBag.Title = "Index";
}
<h2>Currency</h2>
<body>
<div class="converter">
Convert: #Html.TextBoxFor(m => m.ConversionRate, new { #size = "5" })
<div class="form-group">
#Html.Label("Convert from", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Currency List", ViewBag.listCurrencies as SelectList, "Please Select a currency")
</div>
</div>
<div class="form-group">
#Html.Label("Convert to", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Currency List", ViewBag.listCurrencies as SelectList, "Please Select a currency")
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Convert</button>
</div>
</div>
</body>
Couple of things to notice, is the POST action and missing form tag in the view . You created a POST action that accepts Currencies model but the form doesn't post that. Only ConversionRate will bind to the model. To get the "Currency From" and "Currency To" and the "Conversion Rate" you will require a different approach/small changes.
ConversionModel.cs a new Model for index page that will capture your required fields.
public class ConversionModel
{
[Required]//decimal would be better but up to you requirement
public decimal ConversionRate { get; set; }
[Required]
public int FromCurrencyId {get;set;}
public SelectList FromCurrencies {get;set;}
[Required]
public int ToCurrencyId {get;set;}
public SelectList ToCurrencies {get;set;}
}
Get: while there is nothing wrong with what you've done, lets use a model approach and tightly bind it.
public ActionResult Index()
{
CurrenciesClient Cur = new CurrenciesClient();
var listCurrency = Cur.findAll();
ConversionModel model = new ConversionModel();
model.FromCurrencies = new SelectList(listCurrency,"Id", "CurrencyName");
model.ToCurrencies = new SelectList(listCurrency,"Id", "CurrencyName");
return View(model);
}
Post: Important thing here to notice is the SelectList will not be posted back. Only the ConversionRate, FromCurrencyId and ToCurrencyId are sent back not the Lists. If error occurs you will need to rebuild the lists and send it back in the model.
[HttpPost]
public ActionResult Index(ConversionModel curModel)
{
if(ModelState.IsValid)
{
if(curModel.FromCurrencyId ==curModel.ToCurrencyId)
{
//do something if same currecnies and return.
}
else
{
//Get the currencyList with rates from db
//use currency ToCurrencyId and FromCurrencyId to fetch the 2 currencies
// perform conversion with curModel.ConversionRate with existing logic
}
}
//Don'f forget to rebuild the Select Lists...
return View(curModel);
}
View:
#model Project.Model.ConversionModel
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Index", "Currency", FormMethod.Post)
{
#Html.TextBoxFor(m => m.ConversionRate, new { #size = "5" })
#* Please check the syntax *#
#Html.DropDownListFor(m => m.FromCurrencyId , Model.FromCurrencies as SelectList)
#Html.DropDownListFor(m => m.ToCurrencyId , Model.ToCurrencies as SelectList)
<button type="submit" class="btn btn-primary">Convert</button>
}
Not a CUT_COPY_PASTE. please do check for errors if any. It is only an approach.
ajax POST probably the next thing to learn... Let us know.
You need to put your items inside a form like this:
#using (Html.BeginForm("Index", "Currency", FormMethod.Post)
{
// Your form items
}

Adding new data to multiple tables using dropdownlist

Using MVC4 am wanting to implement functionality which will allow a user to add new items to the database.
I've managed to achieve this adding items to a single table, but now I need to display data from multiple tables, then populate the added / selected data to those tables.
I have these 3 tables
Threats
ID
Description
ThreatHasSecurityEvent
ThreatID
SecurityEventID
SecrutiyEvents
ID
Description
And here's my code so far:
ViewModel
public class ThreatWithSecurityEvents
{
public Threat Threat { get; set; }
public SecurityEvent SecurityEvent { get; set; }
public List<int> SecurityEventIds { get; set; }
public ThreatWithSecurityEvents()
{
SecurityEventIds = new List<int>();
}
}
Get Controller
[HttpGet]
public ActionResult AddNewThreat()
{
ThreatWithSecurityEvents ViewModel = new ThreatWithSecurityEvents();
var SecurityEvents = _DBContext.SecurityEvents.Select(x => new SelectListItem()
{
Text = x.Description,
Value = x.ID.ToString()
});
ViewBag.SecurityEventDropdown = SecurityEvents;
return View(ViewModel);
}
View
#model RiskAssesmentApplication.Models.ThreatWithSecurityEvents
#{
ViewBag.Title = "AddNewThreat";
//Layout = "~/Views/Shared/MasterLayout.cshtml";
}
<div style="font-family: Calibri">
<h2>AddNewThreat</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Threat</legend>
#using (Html.BeginForm("Add New Threat", "Threats"))
{
Html.HiddenFor(model => model.SecurityEventIds);
<div class="editor-label">
#Html.LabelFor(model => #Model.Threat.Description, "Threat Description")
</div>
<div class="editor-field">
#Html.EditorFor(model => #Model.Threat.Description)
#Html.ValidationMessageFor(model => #Model.Threat.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => #Model.SecurityEvent.Description, "Associated Security Event")
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.SecurityEventIds, ViewBag.SecurityEventDropdown as IEnumerable<SelectListItem>)
</div>
<p>
<input type="submit" value="Add New" />
</p>
}
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
Am unsure how to implement the Post Action Method and a Save Method in the repository.
Previously I could inject a new Threat Object and send it to the edit view doing something like:
Previous Get Method - AddNewThreat
[HttpGet]
public ActionResult AddNewThreat()
{
return View("EditThreat", new Threat());
}
and I would then use the EditThreat Action Method to post back
Previous Post Action - AddNewThreat
[HttpPost]
public ActionResult EditThreat(Threat Threat)
{
if (ModelState.IsValid)
{
repository.SaveThreat(Threat);
TempData["message"] = string.Format("{0} new description has been saved", Threat.Description);
return RedirectToAction("GetThreat", new { ThreatID = Threat.ID });
}
else
{
// something is incorrect!
return View(Threat);
}
}
Previous Save Method - SaveThreat From Repository
public void SaveThreat(Threat Threat)
{
if (Threat.ID == 0)
{
_context.Threats.Add(Threat);
}
else
{
Threat dbEntry = _context.Threats.Find(Threat.ID);
if (dbEntry != null)
{
dbEntry.Description = Threat.Description;
}
}
_context.SaveChanges();
}
That's as far as I have got so far.
I want the user to be able to enter a new threat description and then select a security event or multiple events from a drop down list which will be associated with the new threat.
I realize am going to have to change the post back action method in the controller and the Save method in my repository, but I cant work out how to get both the new Threat description and the existing security events saved back to the database. I've had a search but as of yet haven't found / understood anything.
Any advice/help would be great.
Thanks
You view model should be
public class NewThreatVM
{
public string Description { get; set; } // add validation attributes as required
public List<int> SelectedSecurityEvents { get; set; }
public SelectList SecurityEventList { get; set; } // or IEnumerable<SelectListItem>
}
Side note: The Threat.ID property is not required in a create view, however if your want to use this for editing an existing Threat as well, add property int? ID and use if (model.ID.HasValue) in the POST method to determine if its a new or existing Threat
and the simplified view
#model yourAssembly.NewThreatVM
#Html.BeginForm())
{
#Html.TextBoxFor(m => m.Description)
#Html.ListBoxFor(m => m.SelectedSecurityEvents, Model.SecurityEventList)
<input type="Submit" value="Create" />
}
Side notes: Your view should not include a hidden input for the Security Event ID's (you cannot bind an input to a complex object or collection)
then the controller
public ActionResult Create()
{
NewThreatVM model = new NewThreatVM model();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Create(NewThreatVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// Initialize new data model and map properties from view model
Threat threat = new Threat() { Description = model.Description };
// Save it (which will set its ID property)
_context.Threats.Add(Threat);
_context.SaveChanges();
// Save each selected security event
foreach (int selectedEvent in model.SelectedSecurityEvents)
{
ThreatHasSecurityEvent securityEvent = new ThreatHasSecurityEvent()
{
ThreatID = threat.ID,
SecurityEventID = selectedEvent
};
_context.ThreatHasSecurityEvents.Add(securityEvent);
}
_context.SaveChanges();
return RedirectToAction("GetThreat", new { ThreatID = threat.ID });
}
private void ConfigureViewModel(NewThreatVM model)
{
var securityEvents = _context.SecurityEvents;
model.SecurityEventList = new SelectList(securityEvents, "ID", "Description");
}
I believe the easiest way to achieve this, is "dividing" your form into separated steps.
You have2 entities: Threats, SecurityEventID
Threat has a collection of SecurityEvents
Create a form to add/edit Threats (url: Threats/Add | Threats/Edit/ThreatId)
Create a form to add/delete Events of an existing Threat (url: Threats/AddEvent/ThreatIdHere
Use custom ViewModels instead of the original class to send data to controller. Examples:
public class AddThreatViewModel
{
public string Description { get; set; }
//since it's a add view model, we dont need a ThreatId here
}
[HttpPost]
public ActionResult AddThreat(AddThreatViewModel model)
{
//convert the view model to Threat, add to database
}
public class AddThreatEvent
{
public int ThreatId { get; set; }
public int SecrutiyEventId { get; set; }
}
[HttpPost]
public ActionResult AddThreatEvent(AddThreatEventmodel)
{
//add threat event into existing threat
}

Pass List data along with ViewModel to view and populate list data in drop down

I have ModelView which I have created for purpose to create new record instance via view-- razor form. In controller I need to assign list data to ViewModel; IEnumerable and then pass this model along with with list data (of CategoryType) which then in view I need to populate in drop-down list, followed by ID of selected CategoryType send back to controller along with other data.
I have assign IEnumerable value to model in controller but not sure is correct and how to do rest part in view ???
View Model - CompanyProfileModelView
public class CompanyProfileModelView
{
public Company _Company { get; set; }
public IEnumerable<CategoryType> _CategoryType { get; set; }
}
Model Class
public class CategoryType
{
public int CategoryTypeID { get; set; }
public string CategoryTitle { get; set; }
public ICollection<Company> Companies { get; set; }
}
Controller Class
[HttpGet]
public ActionResult CreateCompany()
{
var _listData = _appFunctions.GetAllCategory();
var _model = new CompanyProfileModelView
{
_CategoryType = _listData
??????????????
};
return PartialView("_CreateNewCompanyPartial", _model);
}
[HttpPost]
public ActionResult CreateCompany(CompanyProfileModelView _model)
{
try
{
if (ModelState.IsValid)
{
//my code will be here to read for input data
}
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Create New Function Navigation" + ex);
}
return RedirectToAction("Home");
}
View
#model App.DAL.Model.CompanyProfileModelView
#using (Html.BeginForm("CreateCompany", "CompanyProfile", FormMethod.Post, new { id = "NewFunctionNavigationForm" }))
{
<div class="form-group">
#Html.LabelFor(#model => #model._Company.CompanyName, new { #class = "control-label col-md-2" })
<div class="form-group">
#Html.EditorFor(#model =>#model._Company.CompanyName)
#Html.ValidationMessageFor(#model=>#model._Company.CompanyName)
</div>
</div>
<div class="form-group">
// need help here for dropdown of CategoryType list
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
Since DropDownList uses IEnumerable<SelectListItem>, change the view model to
public class CompanyProfileModelView
{
public Company Company { get; set; }
public SelectList CategoryList { get; set; }
}
and assuming Company model contains
[Display(Name="Category")]
public int? CategoryType { get; set; }
Controller
[HttpGet]
public ActionResult CreateCompany()
{
var listData = _appFunctions.GetAllCategory();
var model = new CompanyProfileModelView
{
CategoryList = new SelectList(listData, "CategoryTypeID ", "CategoryTitle")
};
return View(model);
}
[HttpPost]
public ActionResult CreateCompany(CompanyProfileModelView model)
{
if (!ModelState.IsValid)
{
// Re-assign select list if returning the view
var listData = _appFunctions.GetAllCategory();
model.CategoryList = new SelectList(listData, "CategoryTypeID ", "CategoryTitle");
return View(model)
}
// Save and redirect
}
View
#model App.DAL.Model.CompanyProfileModelView
#using (Html.BeginForm()) // Note, no parameters required in this case
{
....
#Html.LabelFor(m => m.Company.CategoryType, new { #class = "control-label col-md-2" })
#Html.DropDownListFor(m => m.Company.CategoryType, Model.CategoryList, "--Please select--")
#Html.ValidationMessageFor(m => m.Company.CategoryType)
.....
<input type="submit" value="Create" class="btn btn-default" />
}

Categories

Resources