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.
Related
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
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.
So what I want to do is take a string from a textarea and pass it to an action method overload (string paramJSON).
Action method:
public ActionResult SendMail(string templateName, string receiver, string paramJSON)
{
var paramDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(paramJSON);
new SendMailClient().Send(templateName, receiver, paramDictionary);
if(Request.IsAjaxRequest())
{
return RedirectToAction("SendPartial", "TestMail");
}
return View();
}
Textarea:
#Html.TextAreaFor(a => a.TestParametrar, new { id = "paramTxt" })
Your html helper
#Html.TextAreaFor(a => a.TestParametrar, new { id = "paramTxt" })
generates a textarea with name="TestParametrar". When you submit a form, it sends back the values of each controls name and value attributes in this case TestParametrar: 'The text you entered' You method needs to include a parameter with the same name, for example
public ActionResult SendMail(string TestParametrar, ....)
and the value of the parameter will be the text entered in the form control.
However, since you view is based on a model, then it is better to just post back to the model and all properties will be bound
public ActionResult SendMail(YourModel model)
which has the added benefit of validating your properties. For example, if property TestParametrar has the [Required] attribute, then if the user does not enter a value, ModelSTate will be invalid and the view can be returned for correction.
#using (Html.BeginForm("SendMail2"))
{
#Html.TextAreaFor(a => a.TestParametrar, new { id = "paramTxt" })
<input type="submit" value="Send Message" />
}
And:
public ActionResult SendMail2(string TestParametrar)
{
return SendMail("myTemplate", "hello#world.com", TestParametrar);
}
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 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.