how can i get the selected text from dropdownlistfor - asp.net-mvc

i have a model :
public class studentmodel
{
public int id { get; set; }
public string name { get; set; }
}
i populate my dropdown :
// GET: dropdown/Test
public ActionResult Index()
{
List<SelectListItem> list = new List<SelectListItem>();
{
list.Add(new SelectListItem { Text = "saurav", Value = "1"});
list.Add(new SelectListItem {Text = "Rj", Value = "2" });
list.Add(new SelectListItem {Text = "rahul", Value = "3" });
ViewBag.studentlist = list;
}
return View();
}
[HttpPost]
public ActionResult Index(studentmodel s)
{
return View();
}
i have a controller action which is postback:
#using (Html.BeginForm("Index", "Test", FormMethod.Post))
{
#Html.DropDownListFor(m => m.name, (IEnumerable<SelectListItem>)ViewBag.studentlist, "select student");
<div>
<input type="submit" value="submit" />
</div>
<div> you have selected : #ViewBag.selected </div>
}
How do i get the text from my drop down list? Thanks

You need to use client side javascript as the change happens at the browser.
First change the markup a little bit to wrap the selection in a span.
<div> you have selected : <span id="selectedItem">#ViewBag.selected</span> </div>
Remove the #ViewBag.selected from the above line if your GET action is not really setting anything to that.
Now the script
$(function(){
$("#name").change(function(){
var selected = $(this).find("option:selected").text();
$("#selectedItem").text(selected);
});
});
This will read the selected option's Text and set that on our span.
If you want this text in the HttpPost action, you can add a new property to your view model
public class studentmodel
{
public int id { get; set; }
public string name { get; set; }
public string SelectedText{ get; set; }
}
And keep a hidden field inside the form
#Html.HiddenFor(s=>s.SelectedText)
Now, set the value of this using javascript set the value of this hidden field.
$(function(){
$("#name").change(function(){
var selected = $(this).find("option:selected").text();
//var selected = $("#name option:selected").text(); // another option
$("#selectedItem").text(selected);
$("#SelectedText").val(selected);
});
});
Now when you submit the form, the value of the hidden field SelectedText will also be submitted.

Model add one viewmodel as below
public class studentmodel
{
public int id { get; set; }
public string name { get; set; }
}
public class SomeViewModel
{
public string studentname {get; set;}
public SelectList studentlist {get; set;}
}
Updated
public ActionResult Index()
{
SomeViewModel Model = new SomeViewModel();
var studentlist = new List<SelectListItem>();
studentlist.Add(new SelectListItem() { Value = "1", Text = "saurav" });
studentlist.Add(new SelectListItem() { Value = "2", Text = "Rj" });
studentlist.Add(new SelectListItem() { Value = "3", Text = "rahul" });
Model.studentlist = new SelectList(studentlist, nameof(SelectListItem.Value), nameof(SelectListItem.Text));
return View(Model);
}
[HttpPost]
public ActionResult Index(SomeViewModel s)
{
return View();
}
and change your view as below
Updated
#model somenamespace.SomeViewModel
#Html.DropDownListFor(m => m.studentname , Model.studentlist , "select student");

Related

Passing Model data from View to Controller

I am trying to pass the Model data from a View (and PartialView within the View) back to the Controller upon HttpPost. (Adapted from Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3)
Why? I want to show a list of assets each with a DropDownList and number of options. Upon submission of form to read the selected items from DropDownList.
My 2 (simplified) models:
public class Booking
{
public int BookingID { get; set; }
public int StoreID { get; set; }
...
public IEnumerable<AssetShort> Assets { get; set; }
}
and
public class AssetShort
{
public int AssetID { get; set; }
....
public int SelectedAction { get; set; }
public IEnumerable<SelectListItem> ActionList { get; set; }
}
In my Booking Controller > Create I build the List:
public ActionResult Booking(int id)
{
// get myBag which contains a List<Asset>
// booking corresponds to 'id'
var myAssets = new List<AssetShort>();
foreach (var a in myBag.Assets)
{
var b = new AssetShort();
b.AssetID = a.ID;
b.SelectedAction = 0;
b.ActionList = new[]
{
new SelectListItem { Selected = true, Value = "0", Text = "Select..."},
new SelectListItem { Selected = false, Value = "1", Text = "Add"},
new SelectListItem { Selected = false, Value = "2", Text = "Remove"},
new SelectListItem { Selected = false, Value = "3", Text = "Relocate"},
new SelectListItem { Selected = false, Value = "4", Text = "Upgrade"},
new SelectListItem { Selected = false, Value = "5", Text = "Downgrade"}
};
myAssets.Add(b);
};
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myAssets.ToList(),
};
return View(model);
My View:
#model uatlab.ViewModels.BookingRequirementsViewModel
#{
ViewBag.Title = "Booking step 2";
}
<h4>Your booking ref. #Model.BookingID</h4>
#using (Html.BeginForm("Booking2", "Booking", FormMethod.Post))
{
<fieldset>
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.StoreID)
#Html.Partial("_Assets", Model.StoreAssets)
<input type="submit" value="Cancel" class="btn btn-default" />
<input type="submit" value="Next" class="btn btn-default" />
</fieldset>
}
The Partial View includes
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
<td>#item.Number</td>
<td>#Html.DropDownListFor(modelItem=>item.SelectedAction, item.ActionList)</td>
</tr>
}
So, all this works fine in the browser and I can select dropdowns for each asset listed but when I submit the only value posted back is the StoreID as it is in a "HiddenFor".
The booking2 controller has the model for a parameter:
public ActionResult Booking2(BookingRequirementsViewModel model)
{
//loop through model.Assets and display SelectedActions
}
Let me make it clear what the problems is - in Booking2 controller the Model is null when viewed in Debug mode and I get error "Object reference not set to an instance of an object."
Any ideas please how to pass back the Model to controller from view?
Regards
Craig
You need to create an EditorTemplate for AssetShort. I also suggest moving ActionList to the BookingRequirementsViewModel so your not regenerating a new SelectList for each AssetShort
The models you have posted aren't making sense. Your controller has var model = new BookingRequirementsViewModel { ..., Assets = myAssets.ToList() }; but in the view you refer to #Html.Partial("_Assets", Model.StoreAssets)? Are these 2 different properties. I will assume that StoreAssets is IEnumerable<AssetShort>
/Views/Shared/EditorTemplates/AssetShort.cshtml
#model AssetShort
<tr>
<td>#Html.DispayFor(m => m.Name)</td>
....
<td>
#Html.DropDownListFor(m => m.SelectedAction, (IEnumerable<SelectListItem>)ViewData["actionList"], "--Please select--")
#Html.ValidationMessageFor(m => m.SelectedAction)
</td>
</tr>
In the main view
#model uatlab.ViewModels.BookingRequirementsViewModel
....
#using (Html.BeginForm()) // Not sure why you post to a method with a different name
{
....
#Html.HiddenFor(m => m.StoreID)
#Html.EditorFor(m => m.StoreAssets, new { actionList = Model.ActionList })
....
}
In the controller
public ActionResult Booking(int id)
{
....
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myBag.Assets.Select(a => new AssetShort()
{
AssetID = a.ID,
SelectedAction = a.SelectedAction, // assign this if you want a selected option, otherwise the "--Please select--" option will be selected
....
})
};
ConfigureViewModel(model); // Assign select list
return View(model);
}
And a separate method to generate the SelectList because it needs to be called in the GET method and again in the POST method if you return the view. Note use the overload of DropDownListFor() to generate the option label (null value) as above, and there is no point setting the Selected property (the value of SelectedAction determines what is selected, not this)
private ConfigureViewModel(BookingRequirementsViewModel model)
{
model.ActionList = new[]
{
new SelectListItem { Value = "1", Text = "Add"},
....
new SelectListItem { Value = "5", Text = "Downgrade"}
};
}
and the POST
public ActionResult Booking(BookingRequirementsViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // Re-assign select list
return View(model);
}
// save and redirect
}
I recommend also making SelectedAction nullable with the [Required] attribute so you get client and server side validation
public class AssetShort
{
public int AssetID { get; set; }
....
[Required]
public int? SelectedAction { get; set; }
}

DropDown in .Net MVC3

I am trying to create a dropdonw in my MVC web application.
Model
namespace projectname.Models
{
public class DropDownModel
{
public int id{get; set;}
puclic string value {get; set;}
}
}
Controller
using projectname.Models;
{
public class DropDownController: Controller
{
public ActionResult Index() //where Index is one of the view
{
List <SelectListItem> listItem = new List<SelectListItem>();
DropDownModel drop = new DropDownModel();
drop.id = 1;
drop.value = "First";
listItem.Add(new SelectListItem() {Value = drop.Value, Text = drop.id.toString()});
return view(listitem);
}
}
}
View
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit http://asp.net/mvc.
</p>
However, the drop down is not being displayed on my Index view.
I would suggest reading more about MVC. You have nothing rendering the dropdown on your view and you have a model that more or less does the same-thing your listitem is doing. This could be handled by one object instead of two. That said :
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
List<SelectListItem> listItem = new List<SelectListItem>();
DropDownModel drop = new DropDownModel();
drop.id = 1;
drop.value = "First";
listItem.Add(new SelectListItem() { Value = drop.id.ToString(), Text = drop.value });
return View(listItem);
}
}
View
Note the #Model List at the top of the view. This defines the strongly typed model asigned to the view. This Model is passed from the controller (listitem) to the view.
#model List<SelectListItem>
#{
ViewBag.Title = "title";
}
#Html.DropDownList("name", Model)
<h2>title</h2>
There are a few ways of display DropDownList in MVC. Here is my way.
Note: You need a collection of SelectListItem in model.
Model
public class MyModel
{
public int SelectedId { get; set; }
public IList<SelectListItem> AllItems { get; set; }
public MyModel()
{
AllItems = new List<SelectListItem>();
}
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel();
model.AllItems = new List<SelectListItem>
{
new SelectListItem { Text = "One", Value = "1"},
new SelectListItem { Text = "Two", Value = "2"},
new SelectListItem { Text = "Three", Value = "3"}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
}
View
#model DemoMvc.Controllers.MyModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
<input type="submit" value="Submit" />
}
You need to give your View the Model which is the listItem.
return View(listItem);

Html.DropDownListFor returns null

There are similar questions and I have tried most of them. Instead of continuing to destroy the remaining code while conjuring demons from the similar past questions, I have decided to ask for help.
When I arrive at the AddMembership action I get a null value instead of the selected item. Below are the details.
View;
#using (Html.BeginForm("AddMembership", "WorkSpace", FormMethod.Post, new { data_ajax = "true", id = "frmAddMembership" }))
{
<div id="newMembershipDiv">
#Html.DropDownListFor(m => m.selectedID, new SelectList(Model.allInfo, "Value","Text",1), "Select!")
<input type="submit" value="Add" name="Command" />
</div>
}
Controller (I just want to see the selectedID or anything appear here.);
public ActionResult AddMembership(SelectListItem selectedID)
{
return View();
}
Model;
public class SomeModel
{
public SelectList allInfo { get; set; }
public SelectListItem selectedID { get; set; }
}
The Monstrosity which initializes the allInfo SelectList
model.allInfo = new SelectList(synHelper.getall().ToArray<Person>().Select(r => new SelectListItem {Text=r.Name, Value=r.prID.ToString() }));
synHelper.getAll() returns a List of the below class;
public class Person
{
public Guid prID { get; set; }
public string Name { get; set; }
}
The only thing that is posted to your action is a selectedID, which is a simple string. If you wander, in the request it looks as simple as:
selectedID=1234
Therefore it should be awaited for as a simple string. Adjust your action parameter:
public ActionResult AddMembership(string selectedID)

Mvc3 DropdownlistFor error

I have a mvc3 dropdownlist containing Organization list.I am able to fill that using the code below.But when I submit the form, I am getting Id instead of name and the corresponding Id is null.
Controller
ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
return view();
Model
public class SubscriberModel
{
public OrgnizationList Organization { get; set; }
public RegisterModel RegisterModel { get; set; }
public SubscriberDetails SubscriberDetails { get; set; }
}
public class OrgnizationList
{
[Required]
public ObjectId Id { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Name")]
public string Name { get; set; }
}
View
#
model FleetTracker.WebUI.Models.SubscriberModel
#using (Html.BeginForm((string)ViewBag.FormAction, "Account")) {
<div>
#Html.DropDownListFor(m => m.Organization.Name, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
</div>
}
When I change it tom => m.Organization.Id, then the modelstate will change to not valid.
Do you really need the name to be returned instead of the Id? If yes then instead of this:
ViewBag.DropDownList =organizationModelList.Select(x => new
SelectListItem { Text = x.Name, Value = x.Id.ToString() });
do this:
ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Name });
Then remove the Required attribute for OrgnizationList.Id. If OrgnizationList is an entity, which I think it is, then you'll run yourself into trouble. I suggest you have a viewmodel that represents your input. So you don't have to deal with unnecessary required fields.
But what if the Name is not unique? Why can't you just accept the Id and save it in your data store? You are not modifying the name of OrgnizationList, I assume.
UPDATE:
If you really need both then tuck the Id on a hidden field:
Your controller method
ViewBag.DropDownList =organizationModelList.Select(x => new SelectListItem { Text = x.Name, Value = x.Id });
Your model
public class SubscriberModel
{
public int OrganizationId { get; set; }
// your other properties goeshere
}
Your view
<div>
#Html.HiddenFor(m=>m.OrganizationId)
#Html.DropDownListFor(m => m.Organization.Name, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
</div>
and a bit of js needed...
$("Organization_Name").change(function(){
$("#OrganizationId").val($(this).val());
});
I did it using
$(document).ready(function () {
$("#DropDownList").change(function () {
$("#Organization_Id").val($(this).val());
$("#Organization_Name").val($("#DropDownList option:selected").text());
});
});
#Html.HiddenFor(m=>m.Organization.Id)
#Html.HiddenFor(m=>m.Organization.Name)
#Html.DropDownList("DropDownList", string.Empty)
controller
ViewBag.DropDownList = new SelectList(organizationModelList, "Id", "Name");

How to show multiple selected with asp.net mvc 3 and ListBoxFor?

I have this VM properties
public IList<Guid> SelectedEligiableCategories { get; set; }
public IList<SelectListItem> EligiableCategories { get; set; }
I have this helpers in my view
#Html.LabelFor(x => x.EligibleCategoryFrmVm.SelectedEligiableCategories, "Eligible Categories:")
#Html.ListBoxFor(x => Model.EligibleCategoryFrmVm.SelectedEligiableCategories, Model.EligibleCategoryFrmVm.EligiableCategories, new { #class = "eligibleCategoryListBox" })
I have this code in my controller
List<SelectListItem> eligibleCategoriesListItems = Mapper.Map<List<EligibleCategory>, List<SelectListItem>>(eligibleCategories);
foreach (var rewardTier in creditCard.RewardTiers)
{
CbRewardTierFrmVm rewardTierFrmVm = new CbRewardTierFrmVm();
rewardTierFrmVm.EligibleCategoryFrmVm.EligiableCategories = eligibleCategoriesListItems;
foreach (var ec in rewardTier.EligibleCategories)
{
rewardTierFrmVm.EligibleCategoryFrmVm.SelectedEligiableCategories.Add(ec.Id);
}
vm.CbRewardTierFrmVm.Add(rewardTierFrmVm);
}
Yet when I load up my view. None of values for my ListBox are selected. I am not sure why. If this was a selectList this would work as it would match up the SelectedEligiableCategories to the value in the list.
I am not sure if this is because there is multiple selects
Edit
<select name="CbRewardTierFrmVm[63b504c0-0f9a-47ba-a8ff-db85f48d5f0f].EligibleCategoryFrmVm.SelectedEligiableCategories" multiple="multiple" id="CbRewardTierFrmVm_63b504c0-0f9a-47ba-a8ff-db85f48d5f0f__EligibleCategoryFrmVm_SelectedEligiableCategories" data-val-required="Must choose at least one eligible category." data-val="true" class="eligibleCategoryListBox ui-wizard-content ui-helper-reset ui-state-default" style="display: none;">
<option value="ed2bb5f9-4565-4f69-ab15-9fca011c0692">Gas</option>
</select>
Do you think it is because I am using http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ ?
Edit2
I gone ahead and make an example. I must be missing something(not sure what). When I use "Darin Dimitrov" it works.
I switched the example to a dropdown as I am getting the same problem with it as well.
In this example I am not using a viewmodel since my initial assumption was somehow the helper I was using from Steven Sanders might be effecting it so I was going off his example.
This does not seem to be the case as I removed it and still get this problem.
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
public string SelectedItem { get; set; }
public IList<SelectListItem> Items { get; set; }
}
public ActionResult Index()
{
List<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem {Value = "",Text ="--"},
new SelectListItem {Value = "1",Text ="1"},
new SelectListItem {Value = "2",Text ="2"},
};
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95, Items = items, SelectedItem = "2" },
new Gift { Name = "Long Cloak", Price = 120.00, Items = items, SelectedItem = "1" }
};
return View("Index3",initialData);
}
#model IList<EditorDemo.Models.Gift>
#{
ViewBag.Title = "Index3";
}
#for (int i = 0; i < Model.Count; i++)
{
#Html.DropDownListFor(x => x[i].SelectedItem, new SelectList(Model[i].Items, "Value", "Text"))
}
It seems to not be able to handle when you put it in forloop and try it make more than one dropdown list.
The following works for me.
Model:
public class MyViewModel
{
public IList<Guid> SelectedEligiableCategories { get; set; }
public IList<SelectListItem> EligiableCategories { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SelectedEligiableCategories = new[]
{
// preselect the second and the fourth item
new Guid("35830042-3556-11E1-BCDC-A6184924019B"),
new Guid("4253876A-3556-11E1-BC17-B7184924019B")
}.ToList(),
EligiableCategories = new[]
{
new SelectListItem { Value = "2DA62E3A-3556-11E1-8A0A-9B184924019B", Text = "item 1" },
new SelectListItem { Value = "35830042-3556-11E1-BCDC-A6184924019B", Text = "item 2" },
new SelectListItem { Value = "3D07EBAC-3556-11E1-8943-B6184924019B", Text = "item 3" },
new SelectListItem { Value = "4253876A-3556-11E1-BC17-B7184924019B", Text = "item 4" },
}
};
return View(model);
}
}
View:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.ListBoxFor(
x => x.SelectedEligiableCategories,
Model.EligiableCategories,
new { #class = "eligibleCategoryListBox" }
)
}
Result:
UPDATE:
Now that you have shown an example allowing to illustrate the problem, you could specify the selected item when building the SelectList:
#Html.DropDownListFor(
x => x[i].SelectedItem,
new SelectList(Model[i].Items, "Value", "Text", Model[i].SelectedItem)
)
The reason a value was not preselected was because you were binding the dropdownlist to a list of properties (x => x[i].SelectedItem) whereas in my example I was using a simple property.
And if you wanted to do this with the ListBoxFor helper you could use the following:
#Html.ListBoxFor(
x => x[i].SelectedItems,
new MultiSelectList(Model[i].Items, "Value", "Text", Model[i].SelectedItems)
)
The SelectedItems property becomes a collection and we use a MultiSelectList instead of a SelectList.
The main problem is using
#Html.DropDownListFor
instead of this
#Html.ListBoxFor
Using the DropDownListFor will NOT help you with multiple values, whatever you do and no matter what your model is. Once you use ListBoxFor ... it will automatically just work !

Resources