How to get drop down value on post back - c#

I have a view with a drop down, which is tied to the view model...
One of the view model's properties:
public int selectDTypeID { get; set; }
the view has a drop down:
Html.DropDownListFor(
model => model.selectDTypeID ,
new SelectList(
new List<Object>{
new { value = 1 , text = "Test1" },
new { value = 2 , text = "Test2" },
new { value = 3 , text = "Test3"}
},
"value",
"text"
)
)
How can I get the the value of the drop down list on post back without using an extra parameter... I'd just like to be able to do this...
[HttpPost]
public ActionResult ContinueDonation(AddDonationViewModel model)
{
var id = model.selectDTypeID;
}
Can I do something like this?

If your View is a strongly typed view like this,
#model AddDonationViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
model => model.selectDTypeID ,
new SelectList(
new List<Object>{
new { value = 1 , text = "Test1" },
new { value = 2 , text = "Test2" },
new { value = 3 , text = "Test3"}
},
"value", "text"))
<input type="submit" value="go" />
}
When you click on submit, the selected value will be available in the SelectdTYpeID property in your HttpPost Action method
[HttpPost]
public ActionResult ContinueDonation(AddDonationViewModel model)
{
var id = model.selectDTypeID; // You have your selected ID here
}

Related

Set the selected value for a DropDownList using SelectListItem

Although this question has been asked for several times, still I am struggling to find a solution for a problem
I have a drop down and i want to bind the selected value when retrieving data.
here is my controller
studentList = db.Students
.Select(x => new SelectListItem
{
Value = x.StudentId.ToString(),
Text = x.StudentNo + " - " + x.StudentNameEn
}).ToList();
ViewData["studentList"] = studentList;
here is my view
#Html.DropDownList("StudentNo", ViewData["studentList"] as List<SelectListItem>, "---Please Select---", new { #class = "form-control selectpicker", id = "studentIdDrp" })
What I have tried
I tried to bind the value using jquery
$("#studentIdDrp").val('#Model.AppointmentViewModel.FK_StudentId');
I tried from the controller to set the selected attribute true
foreach(var item in studentList)
{
if (item.Value == appoinmnetRec.FK_StudentId.ToString())
{
item.Selected = true;
}
}
None of the above methods working. Please help, thanks in advance
I tried to reproduce your issue. In my machine, selected value worked.
Controller:
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
var studentList = new List<SelectListItem>()
{
new SelectListItem {Text = "ABC", Value = "1"},
new SelectListItem {Text = "CDE", Value = "2"},
};
ViewData["studentList"] = studentList;
return View();
}
public ActionResult Student()
{
var studentList = new List<SelectListItem>()
{
new SelectListItem {Text = "Peter Cech", Value = "S001"},
new SelectListItem {Text = "Leo Messi", Value = "S002"},
};
ViewData["studentList"] = studentList;
AppointmentViewModel model = new AppointmentViewModel();
model.FK_StudentId = "S001";
return View(model);
}
}
public class AppointmentViewModel
{
public string FK_StudentId { get; set; }
}
}
View: Student.cshtml
#model WebApplication2.Controllers.AppointmentViewModel
#{
ViewBag.Title = "Student";
}
<h2>Student</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
#Html.DropDownList("StudentNo", ViewData["studentList"] as List<SelectListItem>, "---Please Select---", new { #class = "form-control selectpicker", id = "studentIdDrp" })
<script>
$(document).ready(function () {
$("#studentIdDrp").val('#Model.FK_StudentId');
});
</script>

Pass DropDown List Value from View to Controller

I need to Pass a Value selected from drop down in a View to a Controller and as of now I am failing miserably.
How should I do that?
Following is my code for the View:
#model NurseOneStop.SC.NurseProfile
#{
ViewBag.Title = "Settings";
}
<h2>Settings</h2>
<div class="col-lg-8 col-md-6 profile_detail">
<h3>#Model.Title #Model.FirstName</h3>
<p><span>Profession:</span> #Model.Profession</p>
<p><span>Contact No:</span> <b>#Model.PhoneNumber </b>
<p><span>Email ID:</span> <b>#Model.EmailId </b>
<br />
<br />
<br />
<br />
<div>
<div>
<h5>Visibility Settings for Profile</h5>
#Html.DropDownList("Profile_Settings", new List<SelectListItem>
{
new SelectListItem{ Text="Public", Value = "1" },
new SelectListItem{ Text="Friends Only", Value = "2" },
new SelectListItem{ Text="Private", Value = "3" }
}, "Select Visibility Type")
</div>
<button class="profile_btn">#Html.ActionLink("Save Settings", "UpdateSettings")</a></button>
</div>
</div>
Below is my Controller for the same:
public ActionResult UpdateSettings()
{
NurseProfile objNurseProfile = new NurseProfile();
Int64 NurseId = ApplicationSession.CurrentUser.NurseId;
if (NurseId != 0)
{
//objNurseProfile = objNurseDAL.UpdateProfileVisibility(NurseId, ProfileVisibility);
}
return View(objNurseProfile);
}
Try it with the following code:
[HttpGet]
public ActionResult Settings(Int64? id, string returnUrl)
{
List<Keyword> objKeywordList = new List<Keyword>();
List<SelectListItem> ProfileVisibility = new List<SelectListItem>();
NurseProfileVisibility objNurseProfileVisibility = new NurseProfileVisibility();
Int64 NurseId = ApplicationSession.CurrentUser.NurseId;
objNurseProfileVisibility.NurseId = NurseId;
SelectListItem objSelect = new SelectListItem { Text = "Profile Visibility", Value = "", Selected = true };
objKeywordList = objKeywordDAL.GetKeywordsByType("ProfileVisibility").Results;
var visibilityOption = (from kl in objKeywordList
select new SelectListItem
{
Text = kl.KeywordText,
Value = kl.KeywordValue.ToString(),
Selected = false
}).ToList();
if (id != 0)
{
Result res = objNurseDAL.GetProfileVisibilityById(NurseId);
if (res.Status)
{
if(res.Results != null) {
objNurseProfileVisibility = res.Results;
if (objNurseProfileVisibility.NurseId != NurseId)
{
visibilityOption.FirstOrDefault(x => x.Value == objNurseProfileVisibility.ProfileVisibilityId.ToString()).Selected = true;
}
}
}
}
ViewBag.VisibilityOptions = visibilityOption;
ViewBag.returnUrl = returnUrl;
return View(objNurseProfileVisibility);
}
You need to store the values into the Database and parse them from there using List and DAL's.
You can use razor to fill a dropdownlist like this and then send it via the Model (like MVC dictates).
#{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Public",
Value = "1"
});
listItems.Add(new SelectListItem
{
Text = "Friends Only",
Value = "2"
});
listItems.Add(new SelectListItem
{
Text = "Private",
Value = "3"
});
}
#Html.DropDownListFor(model => model.profileSettings, listItems, "Select Option")
#Html.ActionLink(
"Save Settings", // linkText
"UpdateSettings", // actionName
"Settings", // controllerName
new { // routeValues
SomeModel = Model
},
null // htmlAttributes
)
And you should have your model in your method like so:
public ActionResult UpdateSettings(SomeModel model)
{
int setting = model.profileSettings; //your choice
return View(objNurseProfile);
}
And create a model like so:
public class SomeModel
{
[Required]
public int profileSettings { get; set; }
}

How Do I Bind Values From DropDownListFor To My Controller?

I have a select control with static values in my view and I intend the user select a value and it binds to my controller so I can use it in the required action method.
My View -
#model StockProject.ViewModels.EquityViewModel
#using (Html.BeginForm(FormMethod.Post)){
#{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "BOOKED", Value = "1"},
new SelectListItem {Text = "EXECUTING", Value = "2"},
new SelectListItem {Text = "EXECUTED", Value = "3"},
new SelectListItem {Text = "SUSPENDED", Value = "4"},
new SelectListItem {Text = "CANCELLED", Value = "5"},
}, "Value", "Text");
}
#Html.DropDownListFor(model => model.status, selectList, new { #class = "form-control", name = "status", id = "status" })
<div class="col-md-3 form-group">
<button type="button" class="btn btn-success btn-block form-control" onclick="location.href='#Url.Action("Equity", "Order")'">
Go
<i class="fa fa-arrow-circle-right"></i>
</button>
</div>
}
ViewModel -
public class EquityViewModel
{
public int CustomerId { get; set; }
public string status { get; set; }
public DateTime startdate { get; set; }
public DateTime enddate { get; set; }
public List<ListEquityOrder> ListOrderEquity { get; set; }
public EquityViewModel()
{
ListOrderEquity = new List<ListEquityOrder>();
}
}
Controller -
[HttpGet]
public IActionResult Equity()
{
var modelview = new EquityViewModel();
var model = new EquityRequest();
model.CustomerId = _appSettings.TestCustomerId;
model.RequestStartPoint = 0;
model.NoOfRequests = 1000000;
model.Null = null;
model.Status = modelview.status;
model.StartDate = modelview.StartDate;
model.EndDate = modelview.EndDate;
model.Equity = "EQUITY";
EquityResponse ListEquityOrders = _genericService.CallSoapAction<EquityResponse, EquityRequest>(model, "findCustomerOrdersBySecurityType");
List<ListEquityOrder> findCusOrder = new List<ListEquityOrder>();
foreach (var t in ListEquityOrders.Item)
{
ListEquityOrder listOrder = new ListEquityOrder();
listOrder.BusinessOffice = t.BusinessOffice;
listOrder.CustomerLabel = t.CustomerLabel;
listOrder.CustomerName = t.CustomerName;
listOrder.Exchange = t.Exchange;
listOrder.FixOrderStatus = t.FixOrderStatus;
//adding other data values to the list
findCusOrder.Add(listOrder);
}
modelview.ListOrderEquity = findCusOrder;
return View(modelview);
}
Anytime the user clicks on the submit button, no values are passed the controls - the DropDownListFor and TexBoxes. I have tried FormCollection but that doesn't work. Please how do I resolve this?
You can use the following code getting the expected output.
In your model
public enum BookingDetails
{
BOOKED = 1, EXECUTING = 2, EXECUTED = 3, SUSPENDED = 4, CANCELLED = 5
}
public class SomeModel
{
public BookingDetails bookingDetails { get; set; }
public static IEnumerable<SelectListItem> GetBookingDetailsSelectItems()
{
yield return new SelectListItem { Text = "BOOKED", Value = "1" };
yield return new SelectListItem { Text = "EXECUTING", Value = "2" };
yield return new SelectListItem { Text = "EXECUTED", Value = "3" };
yield return new SelectListItem { Text = "SUSPENDED", Value = "4" };
yield return new SelectListItem { Text = "CANCELLED", Value = "5" };
}
}
Note : The above model only deals with dropdown values. If you want to do more then fell free to extend the class
Then your controller should be like below
public class MyController : Controller
{
// GET: My
public ActionResult MyAction()
{
// shows your form when you load the page
return View();
}
[HttpPost]
public ActionResult MyAction(SomeModel model)
{
var selectedBookingDetails = model.bookingDetails;// this will be the selected dropdown item text.
return View(model);
}
}
then view
#model SomeModel
#using (Html.BeginForm("MyAction", "My", FormMethod.Post))
{
#Html.DropDownListFor(m => m.bookingDetails, SomeModel.GetBookingDetailsSelectItems())
<input type="submit" value="Send" />
}
Note : please include the correct namespace of model

Show Selected value in drop down list on updating in MVC

I am hard coding Gender drop down as it has only two values and it will never be changed.Saving a data base hit.
How do show the selected value on the Edit view so the user can see which gender was selected and easily update it.
Create View
#Html.DropDownList("Departments", new List<SelectListItem>
{
new SelectListItem { Text = "Male", Value = "1"},
new SelectListItem { Text = "Female", Value = "2"}
}, "Select")
Its a little confusing why you are binding a value of 1 or 2 to a property named Department to represent the values "Male" and "Female". I'll assume that you really want to bind to a property named Gender.
Ideally, that property should be typeof string or an enum so that its stored as "Male" or "Female" (the values "1" or "2" wont have much meaning to anyone else).
In addition, you should be generating the SelectList in the controller and passing it to the view (preferably) using a view model or a ViewBag property.
public class PersonVM
[Required(ErrorMessage = "Please select a Gender")]
public string Gender { get; set; } // or use an enum
public IEnumerable<SelectListItem> GenderList { get; set; }
}
In the GET method
PersonVM model = new PersonVM()
{
GenderList = new SelectList(new string[]{ "Male", "Female" }),
Gender = // set this in an Edit method so the correct option is selected
}
// or if not using a view model - ViewBag.GenderList = new SelectList(new string[]{ "Male", "Female" });
return View(model);
and in the view
#Html.DropDownListFor(m => m.Gender, Model.GenderList, "-select-")
// or if not using a view model - #Html.DropDownListFor(m => m.Gender, (SelectList)ViewBag.GenderList, "-select-")
#Html.ValidationMessageFor(m => m.Gender)

Set the selected item in dropdownlist in MVC3

I have to set the selected item for a dropdownlist in view. But its not working.
//View
<div class="editor-label">
#Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Gender,Model.GenderList)
</div>
//Model
[Required(ErrorMessage = "Please select gender!")]
[Display(Name = "Gender")]
public string Gender { get; set; }
public IEnumerable<SelectListItem> GenderList
{
get
{
return new[]
{
new SelectListItem { Value = "0", Text = "Select" },
new SelectListItem { Value = "1", Text = "Male" },
new SelectListItem { Value = "2", Text = "Female" },
};
}
}
The gender property has the value needs to be selected in the list. Still not working.
Where i'm wrong?
First, create your ViewModel.
public class MovieViewModel
{
public string Genre { get; set; }
public IEnumerable<SelectListItem> GenreList
{
get
{
yield return new SelectListItem { Text = "Comedy", Value = "1" };
yield return new SelectListItem { Text = "Drama", Value = "2" };
yield return new SelectListItem { Text = "Documentary", Value = "3" };
}
}
}
Then, your controller creates a new instance of this ViewModel and sends it to the view.
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
var viewModel = new MovieViewModel
{
Genre = "2"
};
return View(viewModel);
}
}
Finally, the view displays the dropdownlist using the ASP.NET wrapper [Html.DropDownListFor()][1].
#model MvcApplication1.Models.MovieViewModel
<!DOCTYPE html>
<html>
<head>
<title>My movie</title>
</head>
<body>
<div>
#Html.DropDownListFor(m => m.Genre, Model.GenreList)
</div>
</body>
</html>
The selected value is then automatically chosen according the ViewModel. There's no need to manually set the Selected property of the objects SelectListitem.
The SelectListItem type has a Selected property, you need to is to true on the item you wish to set as selected.
You can either set it statically like the following:
public IEnumerable<SelectListItem> GenderList
{
get
{
[...]
new SelectListItem { Value = "0", Text = "Select", Selected = true},
[...]
}
}
Or enumerate over the collection for a match with Gender value:
var selected = GenderList.SingleOrDefault(item => item.Text.Equals(this.Gender));
if (selected != null)
selected.Selected = true;

Categories