How to pass value selected from DropDownList to Controller - MVC - html

I am having trouble getting the value selected in my dropdownlist in my Homecontroller. I have the DropDownList in a form but I think my format may be wrong. I'm new to MVC and new to HTML so I'm struggling pretty hard. Would appreciate some help.
Here is my controller (I put this in my homecontroller, is that a bad idea?):
public IActionResult Index()
{
_ = new List<MyjsonSettings>();
var obj = new StatusPortController(configuration);
List<MyjsonSettings> PortList = obj.GetPortNum();
List<SelectListItem> AppNameList = PopulateDropDown(PortList);
ViewData["Applications"] = AppNameList;
return View("~/Views/Home/dataview.cshtml");
}
public List<SelectListItem> PopulateDropDown(List<MyjsonSettings> PortList)
{
List<SelectListItem> AppNameList = new List<SelectListItem>();
for (int i = 0; i < PortList.Count(); i++)
{
AppNameList.Add(new SelectListItem {
Text = PortList[i].NAME, Value = (i+1).ToString()
});
}
return AppNameList;
}
Here is the view (dataview.cshtml):
#{
ViewData["Title"] = "Home Page";
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownList("Applications", ViewData["AppNameList"] as List<SelectListItem>)
<input type="submit" value="submit" />
}
Any ideas? No errors when I run, I just don't know how to get the response back.

you can rebuild the structure to a more usable way, and in order to submit form with drop down list or any type of fields you need to first return a view with Model and then submit the form to an action that receive same Model type as parameter
example:
model:
public class ApplicationsAddModel {
public ApplicationsAddModel (){
//constructer to initialize the list
ApplicationsList = new List<SelectListItem>();
}
public string test{ get; set; }
public int selectedApplicationId { get; set; }
public List<SelectListItem> ApplicationsList { get; set; }
}
controller
//this is the first action that return the model
[HttpGet]
public IActionResult Index()
{
ApplicationsAddModel model = new ApplicationsAddModel ();
//fill your drop down list
List<SelectListItem> AppNameList = PopulateDropDown(PortList);
model.ApplicationsList = AppNameList;
return View(model);
}
[HttpPost] //recive the form
public IActionResult Index(ApplicationsAddModel SubmittedModel)
{
var selectedApplication = SubmittedModel.selectedApplicationId; //get the selected value from ddl
//fill your drop down list
List<SelectListItem> AppNameList = PopulateDropDown(PortList);
model.ApplicationsList = AppNameList;
return View(SubmittedModel);
}
view (index.cshtml):
#model projectName.ApplicationsAddModel
#{ ViewData["Title"] = "Home Page"; }
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.LabelFor(m => m.selectedApplicationId)
#Html.DropDownListFor(m => m.selectedApplicationId, Model.ApplicationsList, "---", new { #class = "custom-select form-control" })
<input type="submit" value="submit" />
}
summary:
in MVC when you have to submit data to controller, create your model, go to controller and create your first action (GET) which fill the form with initial data and fill your drop down lists if exist, then create the (POST) action which receive the model of same type of the view and MVC will bind it automatically for you
best regards

Related

How to pass an array from main view to partial view in asp.net mvc 5

I've a main view that contains an array received from the corresponding Action and it also contains a partial view reference below
Create.cshtml :
#model HrAndPayrollSystem.Models.EmployeeMasterA
#using (Html.BeginForm())
{
ViewData["fs_lbls"] = ViewBag.FS_lbls as string[];
#Html.Partial("~/Views/EmployeeMasterA/FinalSettlementTAB.cshtml", Model)
}
and the referenced partial view above is defined below
FinalSettlementTAB.cshtml :
#model HrAndPayrollSystem.Models.EmployeeMasterA
#Html.DropDownList("DeptId", null, "Department")
/* Print "ViewData["fs_lbls"]" array defined in the Main View `Create.cshtml` here */
I've an array defined in the Create.cshtml, now, I want to pass it into the partial view HR_EmployeeFinalSettlementTAB.cshtml and print it, What is the proper way to to this?
What I've tried :
I changed the #Html.Partial() line into below :
#Html.Partial("~/Views/EmployeeMasterA/FinalSettlementTAB.cshtml", null, new ViewDataDictionary { { "fs_lbls", ViewData["fs_lbls"] } })
and modified the FinalSettlementTAB.cshtml file as below :
#model HrAndPayrollSystem.Models.EmployeeMasterA
#Html.DropDownList("DeptId", null, "Department")
#foreach (var i in ViewData["fs_lbls"] as string[])
{
#i
}
But it throws an exception InvalidOperationException at line #Html.DropDownList("DeptId", null, "Department") by saying :
There is no ViewData item of type 'IEnumerable' that has the key 'DeptId'.
It throws the above exception whenever I try to pass the array data to the partial view using ViewDataDictionary, otherwise, it is working fine, when I'm not.
How do I get rid of the above exception and properly pass array data from main view to the partial view?
I suggest that you add a new property to EmployeeMasterA to store the labels, so that you do not need to use ViewData at all.
public class EmployeeMasterA
{
public string[] fs_lbls { get; set; }
public string SelectedLabel { get; set; }
public List<SelectListItem> Labels
{
get
{
if (this.fs_lbls == null)
{
return Enumerable.Empty<SelectListItem>().ToList();
}
return (from label in fs_lbls
select new SelectListItem
{
Text = label,
Value = label
}).ToList();
}
}
}
Create.cshtml
#model WebApplication1.Controllers.EmployeeMasterA
#using (Html.BeginForm())
{
#Html.Partial("FinalSettlementTAB", Model)
<input type="submit" value="Save"/>
}
FinalSettlementTAB.cshtml
#model WebApplication1.Controllers.EmployeeMasterA
#Html.DropDownList("SelectedLabel", Model.Labels)
Controller
public ActionResult Create()
{
var viewModel = new EmployeeMasterA();
viewModel.fs_lbls = new[] {"Label1", "label 2"};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(EmployeeMasterA viewModel)
{
return View();
}
You can set the content of fs_lbls in the controller action method, before returning the Create view. When you post the form, the SelectedLabel property will contain the selected item from the dropdown list. Obviously you will need to change the property names to suite your needs, but hopefully this will give you an idea.

Post html select to MVC Controller. Finding a better way

I'm just looking for a better way to do the following :
I've got an html select :
<form method="post" action="/Account/ChangeUserRole">
<select name="Val" onchange="this.form.submit();" class="span2">
#foreach (var r in ViewBag.UserRoles)
{
#if (u.UserRole.ID == r.ID)
{
<option selected="selected" value="#u.ID/#r.ID">#r.Name</option>
}
else
{
<option value="#u.ID/#r.ID">#r.Name</option> // <-- better way?
}
}
</select>
</form>
I'm posting it as "userid/roleid" and on the controller side doing a string.Split on / to split u.ID and r.ID
I would like to know if it's possible to post it so my controller get's them in this way :
[HttpPost]
public IActionResult ChangeUserRole(int UserID, int RoleID)
Instead of this witchcraft:
[HttpPost]
public IActionResult ChangeUserRole(string Val)
{
char[] splitChar = new char[] { '/' };
string[] s = Val.Split(splitChar);
int UserID = Convert.ToInt32(s[0]);
int RoleID = Convert.ToInt32(s[1]);
}
Sorry for the long post. Hope my question makes sense.
I'm not such a big fan of html helpers.
Side note:
I'm using MVC 6, ASP 5 - RC1
Appreciate the help
Cheers!
The best solution is to use the TagHelpers to build your dropdown. Let's start by creating a view model specific to this view.
public class UserRoleEditVm
{
public List<SelectListItem> Roles { set; get; }
public int RoleId { set; get; }
public int UserId { set; get; }
}
In your get action, create an object of this, load the property values and send it to the view.
public IActionResult Create()
{
// User Id and Role list is hard coded for demo. You may replace it with real data.
var v = new UserRoleEditVm {UserId = 45};
v.Roles = new List<SelectListItem>
{
new SelectListItem {Value = "1", Text = "Admin"},
new SelectListItem {Value = "2", Text = "Editor"},
new SelectListItem {Value = "3", Text = "Reader"}
};
return View(v);
}
And in your view, which is strongly typed to our view model, we will like Tag helpers to for creating the HTML markup.
#model UserRoleEditVm
<form asp-action="ChangeUserRole" asp-controller="Account">
<select asp-for="RoleId" asp-items="#Model.Roles">
<option>Please select one role</option>
</select>
<input type="hidden"asp-for="UserId"/>
<input type="submit"/>
</form>
And in your HttpPost action method, you can use an object of our view model as the parameter and the Model binder will map the posted form values to property values of that object.
[HttpPost]
public ActionResult ChangeUserRole(UserRoleEditVm model)
{
var userId = model.UserId;
var roleId = model.RoleId;
// to do : Do something with the above 2 values
// to do :Save and redirect (PRG pattern)
// return RedirectToAction("Success");
}

How to get the selected value from the drop down list in MVC 4 and assign that value to another local variable for comparison variable

My Razor View
I want to get the selected value of securityReq_C
#{
var listItems = new List<System.Web.UI.WebControls.ListItem>
{
new System.Web.UI.WebControls.ListItem{Text ="1",Value="1"},
new System.Web.UI.WebControls.ListItem{Text ="2",Value="2"},
new System.Web.UI.WebControls.ListItem{Text ="3",Value="3"}
};
}
#Html.DropDownListFor(x => x.addasset.securityReq_C, new SelectList(listItems, "Value", "Text"), "N/A", new { id = "selectError6", onchange = "getAlldata()" }
You need to have this list on your model and bind the list to your dropdownListFor. You also need to "submit" this somehow i dont know if you use html.BeginForm or ajax.beginform or some other submit function but you will requier to submit the values somehow to your controller. Last but not least you need some function in your Controller to deal with the post from your form or whatever you send back to the controller.
VIEW
using (Ajax.BeginForm("ACTION", "CONTROLLER", new AjaxOptions()
{
HttpMethod = "POST",
OnBegin = "",
OnComplete = "",
UpdateTargetId = "TargetDivToBeUpdated"
}))
{
//Your dropdown Goes inside form
};
CONTROLLER
[HttpPost]
public ActionResult ACTION(MODEL)
{
//Logic
}
MODEL
public class YoURViewModeL
{
public YOuRList { get; set; }
}

Unable to set property on ViewModel when selected option from dropdown List ---MVC4

Unable to find where I'm doing wrong. Help would be appreciated.Thanks!
In my viewmodel I have property ListValues which contain data for dropdownlist. I'm trying to set property(SelectedItem) on viewmodel when a selection is made in dropdownlist. But it is not updating the value when something is selected in dropdownlist. In this example I'm using javascript function to test if the value has been set, but it always says variable undefined.
My ViewModel:
public class ViewModel
{
private readonly List<SelectListItem> items;
public ViewModel()
{
items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "Texas", Value = "1", Selected = true });
items.Add(new SelectListItem() { Text = "Illinios", Value = "2", Selected = false });
items.Add(new SelectListItem() { Text = "New York", Value = "3", Selected = false });
items.Add(new SelectListItem() { Text = "Kansas", Value = "4", Selected = false });
ListValues = items;
}
public string SelectedItem { get; set; }
public IEnumerable<SelectListItem> ListValues { get; set; }
}
Action Method:
public class EmployersController : Controller
{
//
// GET: /Employers/
public ActionResult Index()
{
ViewModel vm = new ViewModel();
return View(vm);
}
}
View:
#using System.Collections
#model DemoMVCApplication.Models.ViewModel
<script src="~/Scripts/Custom/default.js"></script>
#{
ViewBag.Title = "Index";
}
#Html.DropDownListFor(model => model.SelectedItem, Model.ListValues)
<button id="button123" onclick="process(#Model.SelectedItem);">Call Script</button>
<h2>Index</h2>
javascript to test if value has been set
function process(x) {
var result = x;
}
The x always says undefined
this is a duplicate of: How to write a simple Html.DropDownListFor()?
however: <%= Html.DropDownListFor(n => n.MyColorId, new SelectList(Colors, "ColorId", "Name")) %>
is the code from that answer that you require, this being that you also need to convert your type to selectList, despite this already being that type in the Model.

How to pass value of Html.Dropdownlist to Controller

I am dynamically generating a dropdownbox.
I am trying to send the selected value in dropdown box as one of the fields of a model to controller.
#using (Html.BeginForm("AddItem", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label>
Category:</label>
#Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewData["CategoryList"])<br />
<label>
Sku:</label>
#Html.TextBox("newItem.Sku")<br />
<label>
Title:</label>
#Html.TextBox("newItem.Title")<br />
I am able to send all the values as a part of model, except the value of Category(dropdownbox value), hence making the function in controller to fail..
ANSWER: Renaming the Dropdownlist "Category" to = "newItem.Category", did the work, basically it should match the model name.
Create a ViewModel for your Item with Properties to hold all Categories and SelectedCategoryId value
public class ItemViewModel
{
public int ItemId { set;get;}
public string SKU { set;get;}
public string SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories{ get; set; }
}
In your home controller, Create Action method for Add where you create an object of ItemViewModel, Set the Categories and return to the View which is strongly typed.
public ActionResult AddItem()
{
ItemViewModel objNewItem=new ItemViewModel();
objNewItem.Items = new[]
{
new SelectListItem { Value = "1", Text = "Perfume" },
new SelectListItem { Value = "3", Text = "Shoe" },
new SelectListItem { Value = "3", Text = "Shirt" }
};
return View(objNewItem);
}
The Strongly typed View
#model ItemViewModel
#using (Html.BeginForm("AddItem", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
Category:
#Html.DropDownListFor(x => x.SelectedCategoryId ,new SelectList(Model.Categories,"Value",Text"), "Select..")
<input type="submit" value="Add" />
}
And have the HTTPPOST AddItem method in your Home Controller
[HttpPost]
public ActionResult AddItem(ItemViewModel objItem)
{
//Now you can access objItem.SelectedCategoryId and do what you like to do...
}
Your DropDown is bound to a field called Category. So you must have such field on your view model.
public class MyViewModel
{
public string Category { get; set; }
...
}
and your action:
[HttpPost]
public ActionResult AddItem(MyViewModel model)
{
// model.Category will contain the selected value
...
}
Also note that this property must be a simple scalar value (string, int, ...) and not a complex object.
And once you have an adapted view model you could use the strongly typed versions of the helpers:
#model MyViewModel
#using (Html.BeginForm("AddItem", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.LabelFor(x => x.Category)
#Html.DropDownListFor(x => x.Category, Model.Categories)
<br />
#Html.EditorFor(x => x.Sku)
<br/>
#Html.EditorFor(x => x.Title)
...
}
Renaming the Dropdownlist "Category" to = "newItem.Category", did the work, basically if you expect a model to be received in controller, which in this case was "newItem", down control name should match the model name and its property.