Using Html.DropDownList over a SelectList - asp.net-mvc-4

I have the following code inside my model class :-
public class PageOptions
{
public PageOptions()
{
int size = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]);
NameSelectionOptions = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text");
}
public SelectList NameSelectionOptions { get; set; }
}
}
but how i can display the SelectList inside a Html.DropDownList ? and setting the default valueto be size?
Thanks

You simply pass the desired selection as a 4th parameter to the SelectList constructor:
NameSelectionOptions = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text", size); // <<< Add size here
This is far more flexible than selecting a specific item in the list.
There are several options for binding a list to the view. You can use a property in the ViewModel, however standard practice (as per Microsoft's scaffolding templates) is to pass dropdown lists to a view in a ViewBag entry of the same name as the Model property. This has the added bonus of automatically binding the simpler #Html.DropDownList("Size") version to both a Model property called Size and the list in ViewBag.Size.
e.g.
In Controller:
ViewBag.Size = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text", size); // <<< Add size here
viewModel.Size = size;
return View(viewModel);
Where viewModel contains any properties you want edited (including Size).
In View:
#Html.DropDownList("Size")
or if you prefer the strongly typed version.
#Html.DropDownListFor(m=>m.Size, (SelectList)ViewBag.Size)
In any case the consistent naming will help avoid problems.
Default values can go in the ViewBag, but the selection should be bound to your ViewModel so you can use the same ViewModel to receive the posted back values.
#Html.DropDownListFor(m=>m.Size, (SelectList)ViewBag.Size, ViewBag.DefaultSize)
Update:
If you do not wish to bind the current value to anything (as per comment), you simply need to have the ViewBag.Size set to you SelectList by the controller and have this is the View. You do not need a value in the Model.
#Html.DropDownList("Size")
The default selection will be the selection (4th parameter, size) in new SelectList() above.

Simply add Selected property in it:
new SelectListItem { Text=size.ToString(),
Value = size.ToString(),
Selected = true}
Model:
public class PageOptions
{
public PageOptions()
{
int size = Int32.Parse("20");
NameSelectionOptions = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text");
}
public SelectList NameSelectionOptions { get; set; }
public string SelectedValue { get; set; }
}
Action:
public ActionResult Index()
{
PageOptions model = new PageOptions();
return View(model);
}
Strongly Typed View:
#model TestAjaxUpload.Models.PageOptions
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#Html.DropDownListFor(x=>x.SelectedValue,Model.NameSelectionOptions)
if you want to do without changing your current model for view then, create instance inside view and pass like this:
#model SomeModelClass
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#{
TestAjaxUpload.Models.PageOptions objModel = new TestAjaxUpload.Models.PageOptions();
}
#Html.DropDownListFor(x=>x.SelectedValue,objModel.NameSelectionOptions)
but you should add PageOptions SelectList as property in your Model and use it, i don't recommend to do directly in View.
Update (Using ViewBag):
with ViewBag you can do this way:
public ActionResult Index()
{
PageOptions model = new PageOptions();
ViewBag.List = model.NameSelectionOptions;
ViewBag.Selected = "20";
return View(model);
}
in View:
#Html.DropDownListFor(x=>x.SelectedValue,ViewBag.List as SelectList,ViewBag.Selected as string)

Related

How to set default value for a model property which is displayed in a #Html.DropDownList

#model ProjectName.Models.ViewModel
var abc = (IEnumerable<SelectListItem>)ViewData["abc"];
The abc stores all retrieved records and then it displays them via the following html tag:
#Html.DropDownList("abcID", abc , "Select abc ", new { #class = "form-control", required = "required" })
I need to set default value for abcId inside the #Html.DropDownList. How can I do it?
You can refer to the link,Here is a demo worked:
Controller:
public IActionResult SendReport()
{
List<SelectListItem> listAdmin = new List<SelectListItem>();
listAdmin.Add(
new SelectListItem
{
Text = "admin1",
Value = "1"
});
listAdmin.Add(
new SelectListItem
{
Text = "admin2",
Value = "2"
});
ViewBag.listAdmin = listAdmin;
//ViewData["listAdmin"] = listAdmin;
Admin admin = new Admin { id = "2", name = "admin2" };
return View(admin);
}
Admin.cs:
public class Admin
{
public string id { get; set; }
public string name { get; set; }
}
View:
#model Admin
#{
ViewData["Title"] = "SendReport";
}
<h1>View</h1>
<div>
#Html.DropDownListFor(Model => Model.id, new SelectList((IEnumerable<SelectListItem>)ViewBag.listAdmin, "Value", "Text", Model.id), "Selecte", new { #class = "form-control", required = "required" })
</div>
Result:

MVC Core DropDownList selected value ignored

I am trying to access my page at: https://localhost:44319/Analyze/Index/6
The problem is that my drop down list always selects the first item in the list instead of the one provided by ID. While stepping through the debugger, before the View() is returned, I see that the SelectList was populated correctly.
AnalyzeController.cs
public IActionResult Index(int? Id)
{
return Index(Id ?? getStatementEndingById(Id).StatementEndingId);
}
[HttpPost]
public IActionResult Index(int StatementEndingId)
{
var statementEnding = getStatementEndingById(StatementEndingId);
ViewBag.StatementEndingId = new SelectList(
_context.StatementEnding.OrderByDescending(s => s.StatementEndingId),
"StatementEndingId",
"Name",
statementEnding);
return View(getPayments(statementEnding));
}
private StatementEnding getStatementEndingById(int? statementEndingId)
{
StatementEnding statementEnding;
if (statementEndingId.HasValue)
{
statementEnding = _context.StatementEnding.FirstOrDefault(s => s.StatementEndingId == statementEndingId);
}
else
{
statementEnding = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).FirstOrDefault();
}
return statementEnding;
}
Setting DropDownList in Razor
#Html.DropDownList("StatementEndingId", null, new { #class = "form-control mb-2 mr-sm-2" })
I am using ASP.NET Core 2.1.
Any suggestions are much appreciated. Thanks in advance.
First i would recomend to create a typed model, something like this one :
public class StatementViewModel
{
public int StatementEndingId { get; set; }
public List<SelectListItem> StatementEndings { get; set; }
}
Second fill the Model with all dropdown options (StatementEndings) and the selected one (StatementEndingId)
public IActionResult Index()
{
var model = new StatementViewModel();
model.StatementEndingId = getStatementEndingById(Id).StatementEndingId;
model.StatementEndings = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).Select(p => new SelectListItem() { Text = p.Name, Value = p.StatementEndingId }).ToList();
return View(model);
}
And for the last, in the view
#model StatementViewModel
#Html.DropDownListFor(m => m.StatementEndingId, Model.StatementEndings, null, new { #class = "form-control mb-2 mr-sm-2" })

Data not binding to listbox in mvc4

I have listbox
#Html.ListBox("lais", new SelectList(Model.lista, "Value", "Text"), new {#class = "mylistbox"});
Here am getting list data but not binding to listbox (list items value )
This is my action method
public ActionResult PrintRFIDTag()
{
Print p =new Print();
p.lista = GetList();
return View(p);
}
public SelectList GetList()
{
System.Management.ManagementScope objMS =
new System.Management.ManagementScope(ManagementPath.DefaultPath);
objMS.Connect();
List<SelectListItem> items = new List<SelectListItem>();
SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
System.Management.ManagementObjectCollection objMOC = objMOS.Get();
foreach (ManagementObject Printers in objMOC)
{
if (Convert.ToBoolean(Printers["Network"])) // ALL NETWORK PRINTERS.
{
var emptyItem = new SelectListItem()
{
Value = Printers["Name"].ToString(),
Text = "00"
};
items.Add(emptyItem);
}
}
SelectList objselectlist = new SelectList(items,"Value");
return objselectlist;
}
}
Here is my model class
public class Print
{
public SelectList lista { get; set; }
public string Name { get; set; }
}
Returning from view but not binding to listbox
Your help will be appropriated
try this:
#Html.ListBoxFor(m=>m.lista ,Model.lista) and change line SelectList objselectlist = new SelectList(items,"Value"); to this: SelectList objselectlist = new SelectList(items,"Value","Text");

How to get Kendo Dropdown selected should fill Kendo grid

I tried this but from my controller data is returning but not binding to kendo grid
This is my controller
public ActionResult Index(string LocationId)
{
using (var client = new HttpClient())
{
IList<AssetsByLocation> _assetCompanyDetailslist;
AssetRepository assetrep = new AssetRepository();
Guid LocationID = new Guid();
if (Request.Params["LocationId"] != null)
{
LocationID = new Guid(Request.Params["LocationId"].ToString());
_assetCompanyDetailslist = assetrep.GetAssetsForLocation(LocationID);
var model = _assetCompanyDetailslist;
return View(model);
}
else
{
return View();
}
}
}
in my .cshtml kendo grid i used this to read
.Read(read => read.Action("Index", "AssetByLocation").Data("getMsgType"))
This is my event in dropdownlist
.Events(events => events.Change("OnMsgTypeChange"))
There are my functions
var ddlItem;
function getMsgType() {
return {
LocationId: ddlItem
}
}
function OnMsgTypeChange(e) {
ddlItem = this.value();
$("#Grid").data("kendoGrid").dataSource.read();
}
I Finally got with this,
public ActionResult Index([DataSourceRequest]DataSourceRequest request, string LocationId)
{
if (Request.Params["LocationId"] != null)
{
using (var client = new HttpClient())
{
AssetRepository assetrep = new AssetRepository();
Guid LocationID = new Guid();
LocationID = new Guid(Request.Params["LocationId"].ToString());
var msgs = assetrep.GetAssetsForLocation(LocationID).ToDataSourceResult(request);
return Json(msgs);
}
}
else
{
return View();
}
}

MVC 4 multiple buttons in form - why isn't this code working

I am trying to use a variation of the code from this page:
Multiple button in MVC
But everytime I click on the buttons it goes to the index actionresult method and not one of the button methods. Index is the view name but the button clicks are happening in a partial view called "P_NewPersonForm.cshtml"
P_NewPersonForm.cshtml
#using (Html.BeginForm())
{
<div id="divClaimType">
#Html.Label("Claim type:")
#Html.DropDownListFor(m => m.modelClaim.ClaimType, new List<SelectListItem>
{
new SelectListItem{ Text="Legal", Value = "Legal" },
new SelectListItem{ Text="Immigration", Value = "Immigration" },
new SelectListItem{ Text="Housing", Value = "Housing" }
})
</div>
<div id="divClaimStatus" style="padding: 5px;">
#foreach(var item in Model.LinkerStatusOfClaim)
{
#Html.Label("Claim status:")
#Html.DropDownListFor(m => m.LinkerStatusOfClaim[0].ClaimStatusID, new SelectList(Model.modelClaimStatus, "ClaimStatusID", "ClaimStatus"))
#Html.LabelFor(m => m.LinkerStatusOfClaim[0].Notes)
#Html.TextAreaFor(m => m.LinkerStatusOfClaim[0].Notes)
#Html.LabelFor(m => m.LinkerStatusOfClaim[0].StartDate)
#Html.TextBoxFor(m => m.LinkerStatusOfClaim[0].StartDate, new { #id = "datepicker", #Value = DateTime.Now, #readonly = true, Style = "background:#cccccc;" })
<br />
#Html.ValidationMessageFor(model => model.LinkerStatusOfClaim[0].StartDate)
<br />
}
<input type="submit" value="Add another status to this claim..." name="action:add"/>
<input type="submit" value="Delete status." name="action:remove"/>
#* #Ajax.ActionLink("Add another status to this claim...", "AddClaim", "Client", new AjaxOptions { HttpMethod = "POST"})*#
</div>
}
</div>
I have one button for adding to the collection of claims and another to remove one from the collection.
ClientController
public ActionResult Index()
{
var Model = new modelPersonClaim();
// Add one item to model collection by default
LinkerStatusOfClaim LinkerStatusOfClaim = new LinkerStatusOfClaim();
Model.LinkerStatusOfClaim.Add(LinkerStatusOfClaim);
DataLayer.RepositoryClient RC = new RepositoryClient();
Model.isValidModel = true;
RC.GetClaimTypes(Model, PersonTypes.NewPerson.ToString());
return View(Model);
}
[HttpPost]
public ActionResult P_NewPersonForm(modelPersonClaim Model)
{
DataLayer.RepositoryClient RC = new RepositoryClient();
RC.GetClaimTypes(Model, PersonTypes.NewPerson.ToString());
Model.isValidModel = ModelState.IsValid;
if (ModelState.IsValid)
{
RC.CreatePerson(Model);
Model.SuccessfulInsert = true;
Model.InsertString = "Person data has been successfully inserted into the database.";
if (Model.modelClaim.ClaimMade)
{
RC.CreateClaim(Model);
}
}
else
{
Model.SuccessfulInsert = false;
Model.InsertString = "Person data could not be inserted into the database. Missing key fields.";
}
return View("Index", Model);
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
[HttpPost]
[MultiButtonAttribute(Name = "action", Argument = "Add another status to this claim...")]
public ActionResult AddClaimStatus(modelPersonClaim Model)
{
Model.LinkerStatusOfClaim.Insert(Model.LinkerStatusOfClaim.Count, new LinkerStatusOfClaim());
return View("Index", Model);
}
[HttpPost]
[MultiButtonAttribute(Name = "action", Argument = "Delete status.")]
public ActionResult RemoveClaimStatus(modelPersonClaim Model)
{
// Can't remove IF only 1
if (Model.LinkerStatusOfClaim.Count == 1)
{
}
else
{
Model.LinkerStatusOfClaim.RemoveAt(Model.LinkerStatusOfClaim.Count);
}
return View("Index", Model);
}
When I click one the buttons it hits the public override bool IsValidName twice. Once for each button. But then because the action name is always index, it goes to the index method and not one of the button methods.
Does anyone have any ideas how to fix this?
Something is wrong with this part:
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
Your attribute is this:
[MultiButtonAttribute(Name = "action", Argument = "Add another status to this claim...")]
So in that case keyValue will become: "action:Add another status to this claim..." while your HTML states: <input type="submit" value="Add another status to this claim..." name="action:add"/>, so I think Argument in your attribute should be add.