HTML.DropDownListFor not passing parameter to controller? - asp.net-core

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

Related

How do i load data to a drop down on view that already bound with a collection?

i have a view that is bound with the IEnumerable<ProductCategoryViewModel>
in this view there is a drop down box with the values search type values so i can search a product category by either code or name.
here is the controller:
public ActionResult Index()
{
List<SelectListItem> list = new List<SelectListItem> {
new SelectListItem {Text="By Code", Value="1", Selected=true},
new SelectListItem {Text="By Name", Value="2"}
};
var categories = _db.mt_ProductCategories
.Select(
p => new ProductCategoriesViewModel
{
Id = p.Id,
Name = p.CatName,
CatCode = p.CatCode, SearchTypes=list
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
here is the ViewModel
public class ProductCategoriesViewModel
{
public int Id { get; set; }
public string CatCode { get; set; }
public string Name { get; set; }
public IEnumerable<SelectListItem> SearchTypes { get; set; }
public string SearchType { get; set; }
}
here is view
#model IEnumerable<eComm1.Models.ProductCategoriesViewModel>
#using (Ajax.BeginForm("Search", "ProductCategory",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "prod-grid",
InsertionMode = InsertionMode.Replace,
OnSuccess = "loaddivdata"
}))
{
//i need to put the drop down here but since i passed a collection it does not show the property "SearchType". the code should be like below but errors
#Html.DropDownListFor(m=>m.SearchType, Model.SearchTypes)
}
How do i access the property SearchType in my current view?
You need a view model that has properties for SearchType and SearchType and in the view use a single instance of that view model (and initially generate the list of ProductCategories by calling #Html.Action()).
public class ProductSearchVM
{
public string searchText { get; set; }
public string SearchType { get; set; }
public IEnumerable<SelectListItem> SearchTypes { get; set; }
}
and in the controller
public ActionResult Index()
{
ProductSearchVM model = new ProductSearchVM
{
SearchType = "1", // this is how you set the selected value
SearchTypes = new List<SelectListItem>
{
new SelectListItem { Text = "By Code", Value = "1" }, // no point adding Selected = true; - its ignored by the HtmlHelper
new SelectListItem { Text = "By Name", Value = "2" }
}
};
return View(model)
}
and in the view
#model ProductSearchVM
#using (Ajax.BeginForm("Search", "ProductCategory", new AjaxOptions { ... }))
{
#Html.DropDownListFor(m => m.SearchType, Model.SearchTypes)
#Html.TextBoxFor(m => m.searchText)
}
<div id="prod-grid">
#Html.Action("Search", "ProductCategory") // optionally add new { searchType = "1" }?
</div>

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 Populating dropdownlist

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.

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.