ASP.NET MVC Populating dropdownlist - asp.net-mvc-4

I've been trying to populate a dropdownlist for a while now and would appreciate some help. I have my model and viewmodel and my trying to populate the Dropdownlist and send it to the view so a user can choose a cartype and click submit.
public class Cars
{
public int CarId { get; set; }
public string Name { get; set; }
}
public class CarViewModel
{
public int SelectedCarId { get; set; }
public IEnumerable<SelectListItem> CarTypes;
}
public ActionResult FillDropDown()
{
var model = new ViewModel();
model.CarTypes = (from s in context.CarTypes
select new SelectListItem()
{
Text = s.Name,
Value = SqlFunctions.StringConvert((double)s.Id).Trim(),
}).ToList<SelectListItem>();
return View(model);
}
So I would like some help how to render this in the view. I tried the following but I get a nullreference exception.
#Html.BeginForm("FillDropDownList","Home", FormMethod.Post,null)
{
#Html.DropDownListFor(x => x.SelectedCarId, Model.CarTypes);
<input type="submit" value="submit" />
}

Try to use CarViewModel instead of ViewModel.
public ActionResult FillDropDown()
{
var model = new CarViewModel(); //CarViewModel instead of ViewModel
model.CarTypes = (from s in context.CarTypes
select new SelectListItem()
{
Text = s.Name,
Value = SqlFunctions.StringConvert((double)s.Id).Trim(),
}).ToList<SelectListItem>();
return View(model);
}
EDIT:
Change your IEnumerable property in CarViewModel into SelectList
public class CarViewModel
{
public int SelectedCarId { get; set; }
public SelectList CarTypes;
}
Make sure the SelectListItem is not null, in the FillDropDown() method.

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

Passing List from View to Controller - MVC4

I am now kind of stuck here.
I have my Models here
namespace DSS.Models
{
public class SupplierItems
{
public string GroupID { get; set; }
public string GroupName { get; set; }
public List<SupplierLineItems> LineItems { get; set; }
}
}
and have Properties of Supplier Items are defined in Model as
namespace DSS.Models
{
public class SupplierLineItems
{
public string Frequency { get; set; }
public string UnitPrice { get; set; }
public int Index { get; set; }
}
}
My Controller is just hardcoding the Supplier Items and line items
namespace DSS.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public ActionResult GetLineItems(SupplierItems SupplierItems)
{
return View();
}
public ActionResult Index()
{
List<SupplierLineItems> ListOfLineItems = new List<SupplierLineItems>();
SupplierLineItems LineItems = new SupplierLineItems();
LineItems.Frequency = "Regulate";
LineItems.UnitPrice = "20";
LineItems.Index = 1;
ListOfLineItems.Add(LineItems);
SupplierLineItems LineItems1 = new SupplierLineItems();
LineItems1.Frequency = "Regulate";
LineItems1.UnitPrice = "20";
LineItems.Index = 2;
ListOfLineItems.Add(LineItems1);
SupplierItems Items = new SupplierItems();
Items.GroupID = "1";
Items.GroupName = "Core Group";
Items.LineItems = ListOfLineItems;
return View(Items);
}
}
}
Here is my View
#model DSS.Models.SupplierItems
#using DSS.Models
#{
ViewBag.Title = "Home Page";
{
<a type="submit" href="#Url.Action("GetLineItems", "Home", Model)">#Model.GroupName</a>
<br />
foreach (var item in Model.LineItems)
{
#item.Frequency<br />
#item.UnitPrice<br />
#item.Index<br />
}
}
}
When I click on Anchor tag of my view and pass the Model to "GetLineItems" of Home Controller, My Supplier items get passed successfully but List of Line items always comes as null. I am not sure what is going wrong . Anyone, please help
enter code here
You should use ajax post to the controller or simply use form submission to achieve this
instead of using url.action which is an url form of submission

Populating razor DropDownList from view model

I have a custom model (let's say CustomModel) for populating my razor DropDownList in the view:
namespace MyNamespace.Models
{
public class SelectListItem
{
public string Value { get; set; }
public string Text { get; set; }
}
public class ComponentTypeModel
{
private readonly List<ComponentType> componentTypes;
[Display(Name = "Component Type")]
public int SelectedCompTypeId { get; set; }
public IEnumerable<SelectListItem> CompTypeItems
{
get
{
var allCompTypes = componentTypes.Select(f => new SelectListItem
{
Value = f.Id.ToString(),
Text = f.Name
});
return allCompTypes;
}
}
public IEnumerable<SelectListItem> DefaultCompTypeItem
{
get
{
return Enumerable.Repeat(new SelectListItem
{
Value = "-1",
Text = "Select a component type"
},
count: 1);
}
}
}
}
Then in my view I do the following using razor:
#model MyNamespace.Models.CustomModel
#Html.LabelFor(m => m.SelectedCompTypeId);
#Html.DropDownListFor(m => m.SelectedCompTypeId, Model.CompTypeItems);
but the second argument Model.CompTypeItems in line:
#Html.DropDownListFor(m => m.SelectedCompTypeId, Model.CompTypeItems);
is generating a compilation error saying that it is not valid. Any ideas?
I think you are complicating yourself.
Just use this model:
public class ComponentTypeModel
{
public int? SelectedComp {get; set;}
public SelectList DDLCompTypes {get; set;}
}
Then in your controller:
var model = new ComponentTypeModel();
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name");
//If you need to set some value in the DropDownValue (for instance in the Edit view) you do:
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name", model.SelectedComp);
Then in your View:
#Html.DropDownFor(x => x.SelectedComp, Model.DDLCompTypes, "Select a component type" )

"inline" editing in a mvc 4 list of objects

I have a strange problem and I don't know if this is actually possible.
What I want is, to be able to list all the values from my model and and edit them directly in the list.
Here's what I have:
Model Linker:
public class StoreLinkerModel
{
//public Guid? id { get; set; }
public IEnumerable<Stores> StoresAndOpeninghours { get; set; }
}
public class Stores
{
public long ID { get; set; }
public string StoreName { get; set; }
public string Address { get; set; }
public string Zip { get; set; }
public string City { get; set; }
}
My Controller:
public ActionResult Overview()
{
var model = new StoreLinkerModel
{
StoresAndOpeninghours = new[]
{
new Stores()
{
ID = 0,
Address = "Enghavevej 70"
},
new Stores()
{
ID=1,
Address = "Løngangsgade 30"
},
}
};
return View(model);
}
[HttpPost]
public ActionResult Overview(StoreLinkerModel model)
{
if (ModelState.IsValid)
{
var x = "go go go";
}
return RedirectToAction("Overview");
}
My overview.aspx page:
#model streetoffrs.web.Models.StoreLinkerModel
#{
ViewBag.Title = "Overview";
Layout = "~/Views/Shared/_dashboard.cshtml";
}
#Html.EditorFor(x => x.StoresAndOpeninghours)
and my EditorTemplate stores.aspx
#model streetoffrs.web.Models.Stores
#using (Html.BeginForm("Overview", "Dashboard", FormMethod.Post, new { name = "id" + #Html.DisplayFor(m => m.ID) }))
{
#Html.EditorFor(x => x.Address)
<input type="submit" class="left btn btn-primary" value="Ret butiksdata">
}
<br />
The list is being generated as it should, and when I hit the first button at the first editorfor it will post the model to my controller, but when I push the 2nd button, the model is null, but the first button still works!
Is this possible at all, if yes what am I missing, if not, tell me how I can accomplish this.
thanks in advance!
you need edit post action like this:
[HttpPost]
public ActionResult Overview(StoreLinkerModel model)
{
if (ModelState.IsValid)
{
var x = "go go go";
}
return View(model);
}
the RedirectToAction will be go to the first Overview Action,so you will be lost the data.

MVC submit multiple objects in model when form post

I am facing a problem that when I have a complex Model, if I submit the form it will not give me all the values of all the model properties, in the below example, I am not getting back the gridModel properties:
Model
public class InventoryModel {
public GridModel GridModel { get; set; }
public Int32 UserKey { get; set; }
}
public class GridModel {
public String GridId { get; set; }
public String GridName { get; set; }
public List<String> columns { get; set; }
}
Controller
public ActionResult Index(){
InventoryModel model = new InventoryModel();
model.UserKey= 20014;
model.GridModel = new GridModel();
model.GridModel.GridId = "jqgInventory";
model.GridModel.GridName = "Inventory Grid";
return View(model);
}
[HttpPost]
public ActionResult Index(InventoryModel model){
Int32 userId = model.UserKey; // This has a value
String gridId = model.GridModel.GridId; // This doesn't have a value
String gridName= model.GridModel.GridName; // This doesn't have a value
}
View
#model InventoryModel
#using (Html.BeginForm()) {
#Html.TextBoxFor(m => m.UserKey, new { #class = "w200" })
#Html.TextBoxFor(m => m.GridModel.GridId , new { #class = "w200" })
#Html.TextBoxFor(m => m.GridModel.GridName, new { #class = "w200" })
<input type="submit" value="Submit" />
}
Any suggestion please would be appreciated.
Thanks,
Alaa
You could instead use a ViewModel rather than the actual Model. This would be a flatter class that reflects the data specifically for the View.
public class InventoryViewModel{
Int32 UserKey {get; set; }
public String GridId { get; set; }
public String GridName { get; set; }
}
Your controller can map your model to your ViewModel if necessary