dropdown population with viewmodel asp.net mvc - asp.net-mvc-4

i am new in MVC. so when see code to understand then some time confusion occur. here i am giving a code. so please see the code first.
public class ProductViewModel
{
public int ID { set;get;}
public string Name { set;get;}
}
public class OrderViewModel
{
private List<ProductViewModel> _products;
public int OrderNumber { set; get; }
public List<ProductViewModel> Products
{
get
{
if (_products == null)
{
_products = new List<ProductViewModel>();
_products.Add(new ProductViewModel { ID = 1, Name = "Ketchup" });
_products.Add(new ProductViewModel { ID = 1, Name = "Mustard" });
_products.Add(new ProductViewModel { ID = 1, Name = "Relish" });
_products.Add(new ProductViewModel { ID = 1, Name = "Mayo" });
}
return _products;
}
}
public int SelectedProductId { set;get;}
}
public ActionResult Order()
{
OrderViewModel orderVM = new OrderViewModel();
return View(orderVM);
}
#model ORderViewModel
#using (Html.BeginForm())
{
<p>
#Html.DropDownListFor(x => x.SelectedProductId , new SelectList(Model.Products, "Value", "Text"), "-- Select Product--")
</p>
}
my question is can i place this code public int SelectedProductId { set;get;} in ProductViewModel instead of OrderViewModel.
if it is possible then what to change in code and in view html ?

Related

HTML.DropDownListFor not passing parameter to controller?

i am trying to filter my view for a couple of hours by now. This is what i have:
My View:
#using (Html.BeginForm("Index", "RH_CentroCusto", FormMethod.Get))
{
#Html.DropDownListFor(f => f.DepartmentoSelecionado , Model.Departamentos, "Select")
}
in my Model Class :
public IEnumerable<SelectListItem> Departamentos { get; set; }
public string DepartmentoSelecionado { get; set; }
My controller:
//i want to receive the value in departamentoSelecionado !!
public IActionResult Index( string searchString, string departamentoSelecionado = "", int page = 1)
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (var x in _context.RH_Departamento.ToList())
{
selectList.Add(new SelectListItem() { Text = x.Departamento , Value = x.Departamento });
}
//and then i add to the viewModel that i create the list
ViewModelCentroCusto vmcc = new ViewModelCentroCusto()
{
Departamentos = selectList
}
When i try to select one and click enter, it is suposed to be passing because in my browser i inspected and it was passing query parameters:
But in my controller my departamentoSelecionado is null, also the dropdown list gets the "select" again instead of keeping what i choose before! Any help is appreciated!
Change departamentoSelecionado to departmentoSelecionado . You spelt an extra letter a in departmentoSelecionado .
//public IActionResult Index( string searchString, string departamentoSelecionado = "", int page = 1)
public IActionResult Index( string searchString, string departmentoSelecionado = "", int page = 1)
The parameter in action method should be same as f => f.DepartmentoSelecionado.
Update 16/09/2020
Codes of controller
public class RH_CentroCustoController : Controller
{
//i want to receive the value in departamentoSelecionado !!
public IActionResult Index(string searchString, string departmentoSelecionado ="", int page = 1)
{
List<SelectListItem> selectList = new List<SelectListItem>();
IList<RH_Departamento> RH_Departamento = new List<RH_Departamento>(){
new RH_Departamento(){ Departamento="dep1" },
new RH_Departamento(){ Departamento="dep2" },
new RH_Departamento(){ Departamento="dep3" },
};//just for test
//foreach (var x in _context.RH_Departamento.ToList())
foreach (var x in RH_Departamento.ToList())
{
selectList.Add(new SelectListItem() { Text = x.Departamento, Value = x.Departamento });
}
//and then i add to the viewModel that i create the list
ViewModelCentroCusto vmcc = new ViewModelCentroCusto()
{
Departamentos = selectList
};
return View(vmcc);
}
}
Codes of View
#model xxx.Models.ViewModelCentroCusto
#{
Layout = null;
}
#using (Html.BeginForm("Index", "RH_CentroCusto", FormMethod.Get))
{
#Html.DropDownListFor(f => f.DepartmentoSelecionado, new SelectList(Model.Departamentos, "Value", "Text"), "Select");
<input type="submit" value="Save" />
}
Codes of Model
public class ViewModelCentroCusto
{
public IEnumerable<SelectListItem> Departamentos { get; set; }
public string DepartmentoSelecionado { get; set; }
}
public class RH_Departamento
{
public string Departamento { get; set; }
}
Test

ASP.Net MVC: How to bind dropdown with deep nested property

suppose below is my view model classes.
public class MainViewModel
{
public List<Student> Students { get; set; }
public int SelectedState = 0;
}
public class Student
{
public int ID = 0;
public string Name = "";
public int StateID = 0;
public List<States> States { get; set; }
}
public class States
{
public int ID = 0;
public string Name = "";
}
now how could i bind dropdown with nested property called States of student class ?
#Html.DropDownListFor(x => x.SelectedState new SelectList(Model.Students.States, "ID", "Name", Model.SelectedState), "-- Select States--", new { id = "cboState", #class = "edit-mode" })
this is not working SelectList(Model.Students.States, "ID", "Name", Model.SelectedState) how to refer this Model.Students.States
please discuss this issue with code sample. each student has relation with states.
Check this out:
#Html.DropDownListFor(x => x.SelectedState, new SelectList(Model.Students.FirstOrDefault().States, "ID", "Name", Model.SelectedState), "-- Select States--", new { id = "cboState", #class = "edit-mode" })
But its better to save States List in ViewBag in your Controller:
ViewBag.States = (_context or _serviceLayer).(States or GetStates()).Select(s => new SelectListItem { Value = s.ID, Text = s.Name, Selected = s.ID == viewModel.SelectedState }).ToList();
And on View:
#Html.DropDownListFor(x => x.SelectedState, (List<SelectListItem>)ViewBag.States, "-- Select States--", new { id = "cboState", #class = "edit-mode" })
REQUESTED EDIT:
Models:
namespace MyProject.Models
{
public class ViewInfo
{
public int StateID { get; set; }
}
public class Student
{
public int ID { get; set; }
public string FullName { get; set; }
public int StateID { get; set; }
}
public class State
{
public int ID { get; set; }
public string Name { get; set; }
}
}
Controllers:
using MyProject.Models;
namespace MyProject.Controllers
{
public class StudentsController : Controller
{
private MyDBEntities _context;
public StudentsController()
{
this._context = new MyDBEntities();
}
// StudentsController
public ActionResult Index()
{
ViewBag.ViewInfo = new ViewInfo { StateID = 1 };
ViewBag.StateID = _context.States.Select(s => new SelectListItem { Value = s.ID, Text = s.Name }).ToList();
return View(_context.Students.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ViewInfo viewInfo)
{
ModelState.Clear();
ViewBag.ViewInfo = viewInfo;
ViewBag.StateID = _context.States.Select(s => new SelectListItem { Value = s.ID, Text = s.Name, Selected = s.ID == viewInfo.StateID }).ToList();
return View(_context.Students.Where(s => s.StateID == viewInfo.StateID).ToList());
}
}
}
And the View:
#using MyProject.Models;
#model IEnumerable<MyProject.Models.Student>
#{
ViewBag.Title = "Students";
ViewInfo viewInfo = ViewBag.ViewInfo;
}
<div class="page-header">
<h2>Students</h2>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
#Html.DropDownList("StateID", null, new { #class = "form-control" })
<input type="submit" value="Filter" class="btn btn-primary" />
// Students Table
}

How to post dropdownlist viewbag values to sql server using mvc 4?

I am getting dynamic values in dropdownlist through viewbag,dropdownlist values is displaying properly but my problem is posting,I am getting problem to insert dropdownlist values in sql server,please help me to solve this problem.
This is my model page,
public class RegisterModel
{
public Prefix Prefix { get; set; }
}
public class Prefix
{
public int? ID { get; set; }
public string Name { get; set; }
}
This is my controller page,
void BindPrefix()
{
List<Prefix> lstPrefix = new List<Prefix>()
{
new Prefix { ID = null, Name = "Select" },
new Prefix { ID = 1, Name = "Mr" },
new Prefix { ID = 2, Name = "Ms" },
new Prefix { ID = 1, Name = "Mrs" },
new Prefix { ID = 2, Name = "Dr" }
};
ViewBag.Prefix = lstPrefix;
}
public ActionResult Register()
{
BindPrefix();
return View();
}
[HttpPost]
public ActionResult Register(FormCollection FC)
{
string Prefix =FC[ViewBag.Prefix]; // here prefix get null value.
return view();
}
This is my view page,
#Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))
If you are trying to get Selected Value,You have to get from the Drop down name which generate:
string Prefix =FC["Prefix"];
Currently this :
#Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))
will generate this html:
<select id="Prefix_ID" name="Prefix.ID">
.........
.........
</select>
and using Element name in form Collection will give you the value.
string Prefix =FC["Prefix.ID"].ToString();
Based on the comments that you only want to display and post back a 'title', the use of class Prefix seems unnecessary
View model
public class RegisterViewModel
{
[Required(ErrorMessage = "Please select a title")]
public string Title { get; set }
// other properties
public SelectList TitleList { get; set; }
}
Controller
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if(!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
}
private void ConfigureViewModel(RegisterViewModel model)
{
List<string> titles = new List<string>) { "Mr.", "Ms", "Mrs", "Dr." };
model.TitleList = new SelectList(titles);
}
View
#model RegisterViewModel
...
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Title)
#Html.DropDownListFor(m => m.Title, Model.TitleList, "-Please select-")
#Html.ValidationMessageFor(m => m.Title)
....
}

Asp.net MVC , CheckBoxs not binding in case of list

Though it seems like it has been discussed earlier also , but I could not find the solution -:
I have a VM like this-:
public class RoomsVm
{
public RoomsVm()
{
Rooms.Add(new Room()
{
IsVip = true,Id = "1"
}
);
Rooms.Add(new Room()
{
IsVip = false,
Id = "2"
}
);
}
public List<Room> Rooms=new List<Room>();
}
public class Room
{
public bool IsVip { get; set; }
public string Id { get; set; }
}
My controller has 2 simple actions- 1- for get and 2 for post-:
public ActionResult IndexView2()
{
var roomVM = new RoomsVm();
return View(roomVM);
}
[HttpPost]
public ActionResult IndexView2(RoomsVm roomsVm)
{
return View(roomsVm);
}
In my view - I simply display my rooms with check boxes like this-:
#model MVCApplication.Models.RoomsVm
<h2>IndexView2</h2>
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Rooms.Count(); i++)
{
#Html.CheckBoxFor(modelItem=>modelItem.Rooms[i].IsVip,new{value=Model.Rooms[i].Id})
}
<input type="submit" value="Submit"/>
}
Problem- When I click Submit button, I don't get updated values of rooms checkboxes in input value of Post action ..
What wrong am I doing ?
You don't have accessors on your Rooms property
public class RoomsVm
{
public RoomsVm()
{
Rooms = new List<Room>(); // Initialize rooms
Rooms.Add(new Room() {.... //Add rooms
}
public List<Room> Rooms { get; set; } // Add get/set
}

DropDownList with possible nested DropDownList in MVC4

I have a set of questions the user can choose from and some of those questions have a secondary list of options to choose from. My goal is to have a drop down list and if you pick one of the options that has items in its SecondaryChoiceList then a second list would appear below the initial dropdown and all of this would be strongly typed and bound to the model upon submission.
I can get the initial list to appear by saying:
#Html.DropDownListFor( x => x.SelectedChoiceId, new SelectList(Model.Choices, "Id", "Name"))
But that has no hooks to the secondary list and I am completely lost as to how I would tie that secondary list back to the model that is returned when I submit the form.
Here's my view model:
public class ExampleViewModel
{
public List<Choice> ChoiceList { get; set; }
public int SelectedChoiceId { get; set; }
public int SelectedAffiliateId { get; set; }
}
Here is what a Choice looks like:
public class Choice
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<SecondaryChoice> SecondaryChoiceList { get; set; }
public Choice()
{
SecondaryChoiceList = new List<SecondaryChoice>();
}
}
And here is my SecondaryChoice object:
public class EligibleAffiliate
{
public int Id { get; set; }
public int EligibilityChoiceId { get; set; }
public string Name { get; set; }
}
If there is anything that I can clear up let me know.
I have tried to keep it as simple as possible.
So, a sample model is given below:
namespace StackOverflow.Models
{
public class Choice
{
public int Id { get; set; }
public string Name { get; set; }
public Choice()
{
Id = 0;
}
public Choice(int id, string name)
{
Id = id;
Name = name;
}
}
}
namespace StackOverflow.Models
{
public class ExampleViewModel
{
public List<Choice> PrimaryChoiceList { get; set; }
public List<Choice> SecondaryChoiceList { get; set; }
public int SelectedChoiceId { get; set; }
public int SelectedAffiliateId { get; set; }
public ExampleViewModel()
{
SelectedChoiceId = 0;
SelectedAffiliateId = 0;
PrimaryChoiceList = new List<Choice>()
{
new Choice(1, "How are you?"),
new Choice(2, "How is the weahter?"),
new Choice(3, "What have you been doing so far?"),
new Choice(4, "What's up man?"),
new Choice(5, "Any news?"),
new Choice(5, "Bla bla bla")
};
SecondaryChoiceList = new List<Choice>()
{
new Choice(1, "How are you dear?"),
new Choice(2, "How is the weahter?"),
new Choice(3, "What have you been doing so far dear?"),
new Choice(4, "What's up man?"),
new Choice(5, "Any romantic news?")
};
}
}
}
Sample controller:
namespace StackOverFlow.Controllers
{
public class SOController : Controller
{
public static ExampleViewModel evm = new ExampleViewModel();
public ActionResult Index()
{
return View(evm);
}
public ActionResult SetSelection(int id)
{
evm.SelectedChoiceId = id;
if (evm.PrimaryChoiceList.Count() > 0)
{
Choice selection = evm.PrimaryChoiceList.ElementAt(id-1);
Choice affiliate = (Choice)evm.SecondaryChoiceList.FirstOrDefault(x => x.Name == selection.Name);
if (affiliate != null)
{
return Content("show");
}
else
{
return Content("hide");
}
}
else
{
return Content("hide");
}
}
}
}
And the web page:
#using StackOverflow2.Models;
#model ExampleViewModel
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
#{
ViewBag.Title = "Stackoverflow Sample";
}
<h2>Index</h2>
<script type="text/javascript">
// Get the selection and make Ajax Request to the controller, action: SetSelection,
// which in turn may decide whetger you must show or hide the control
function updateSeconadryQuestion(id) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText == 'show')
$('#SecondaryQuestionDropBoxId').show();
else
$('#SecondaryQuestionDropBoxId').hide();
}
}
xmlhttp.open("GET", "/SO/SetSelection?id=" + id, true);
xmlhttp.send();
}
</script>
#Html.DropDownListFor(x => x.SelectedChoiceId, new SelectList(Model.PrimaryChoiceList, "Id", "Name", "Value"), new { id = "PrimaryQuestionDropBoxId", onchange = "updateSeconadryQuestion(value);" })
<div id="SeconadryQuestionDivId">
#Html.DropDownListFor(x => x.SelectedAffiliateId, new SelectList(Model.SecondaryChoiceList, "Id", "Name"), new { id = "SecondaryQuestionDropBoxId" })
</div>