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; }
}
Related
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>
I want to fill dropdownlist countries based on User login into my application. If user is not logged on then the default country will be displayed. Please help me and guide me how to fill dropdown based on user logon country. Any help is highly appreciated.
AspUsers table -- When user register, all the information goes to this table
My LeadingClass data Model
public int? Type { get; set; }
public string Country { get; set; }
My LeadingFilterVM View Model
public int? Type { get; set; }
public IEnumerable<SelectListItem> TypeList { get; set; }
public string Country { get; set; }
public IEnumerable<SelectListItem> CountriesList { get; set; }
public IPagedList<LeadingClass> Leadings { get; set; }
My LeadingDatabaseHandle
public List<LeadingClass> LeadingBasedonFilter(int? Type, string Country = "")
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<LeadingClass> leadingClass = new List<LeadingClass>();
string sSQL;
SqlParameter[] prms = new SqlParameter[3];
sSQL = "exec GetLeeading #Type,#country";
prms[0] = new SqlParameter("#Type", SqlDbType.Int);
prms[0].Value = Sire;
prms[1] = new SqlParameter("#Country", SqlDbType.VarChar);
prms[1].Value = Country;
ds = clsUtilities.CreateCommandwithParams(sSQL, prms);
DataTable dataTable = ds.Tables[0];
foreach (DataRow dr in dataTable.Rows)
{
leadingClass.Add(
new LeadingClass
{
Id = Convert.ToInt32(dr["Id"]),
Name= Convert.ToString(dr["Name"]),
}
);
}
return leadingClass;
}
My Home Controller
[HttpGet]
public ActionResult Leading(int? type, string country,int? pageNumber)
{
LeadingDatabaseHandle leadingDatabaseHandle = new LeadingDatabaseHandle();
IEnumerable<LeadingClass> data;
if (type!=null)
{
data = leadingDatabaseHandle.LeadingBasedonFilter(type.Value, country);
}
else
{
data = leadingDatabaseHandle.LeadingSiresAll();
}
LeadingFilterVM model = new LeadingFilterVM
{
Type = type,
Country = country,
TypeList = new List<SelectListItem>
{
new SelectListItem{ Text = "General", Value = "1" },
new SelectListItem{ Text = "Advance", Value = "2" },
},
CountriesList = new List<SelectListItem>
{
new SelectListItem {Value = "NZ", Text="New Zealand" },
new SelectListItem {Value = "AUS", Text = "Australia" },
new SelectListItem {Value = "FR", Text = "France" },
new SelectListItem {Value = "GB", Text = "Great Britain" },
},
Leadings = data.ToPagedList(pageNumber ?? 1, 10)
};
return View(model);
}
My Leading View
#using (Html.BeginForm("Leading", "Home", FormMethod.Get))
{
<div class="col-sm-2">
#Html.DisplayNameFor(m => m.Leadings.FirstOrDefault().Type)
#Html.DropDownListFor(m => m.Type, Model.TypeList, new { #class = "form-control" })
</div>
<div class=" col-sm-2">
#Html.DisplayNameFor(m => m.Country)
#Html.DropDownListFor(m => m.Country, Model.CountriesList, new { #class = "form-control"})
</div>
<button type="submit" class="btn btn-info">Search</button>
}
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
When this code runs, checkbox items are missing their labels, and any selection in a checkbox crashes/fails the page.
View (Index.cshtml)
#using stupidassTests.Models
#model MyViewModel
#{
ViewBag.Title = "Index";
}
<h2>Password Input</h2>
<div>
<p>Enter Password</p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
#Html.TextBox("password")
<button type="submit" value="Search"></button>
}
<p>#Model.input.passWord</p> <!--passWord is underlined with red because it conflicts with the List'model'-->
</div>
<h2>Checkbox</h2>
<div>
#using (Html.BeginForm())
{
for (var i = 0; i < 10; i++)
{
<p>
#Html.HiddenFor(n => n.inputCollection[i].Id)
#Html.DisplayFor(n => n.inputCollection[i].Name)
#Html.HiddenFor(n => n.inputCollection[i].Name)
#Html.CheckBoxFor(n => n.inputCollection[i].Checked)
</p>
}
<input id="Submit1" type="submit" value="submit" />
if (ViewBag.Values != null)
{
foreach (var item in ViewBag.Values)
{
<p>#item</p>
}
}
}
Model (FormInputs.cs):
public class MyViewModel
{
public FormInputs input { get; set; }
public List<FormInputs> inputCollection { get; set; }
public bool isList { get; set; }
}
public class FormInputs
{
public string passWord = "";
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
public List<string> checkBox = new List<string>();
}
Controller (HomeController.cs):
public ActionResult Index()
{
return View();
}
[HttpGet, ActionName("Index")]
public ActionResult PasswordInput(string password)
{
FormInputs pss = new FormInputs();
pss.passWord = password;
MyViewModel mvm = new MyViewModel() { input = pss, isList = false };
return this.View("Index", mvm);
}
[HttpGet]
public ActionResult CheckBoxGet()
{
var list = new List<FormInputs>
{
new FormInputs { Id = 1, Name = "Aquafina", Checked = false },
new FormInputs { Id = 2, Name = "Mulshi Springs", Checked = false },
new FormInputs { Id = 3, Name = "Alfa Blue", Checked = false },
new FormInputs { Id = 4, Name = "Atlas Premium", Checked = false },
new FormInputs { Id = 5, Name = "Bailley", Checked = false },
new FormInputs { Id = 6, Name = "Bisleri", Checked = false },
new FormInputs { Id = 7, Name = "Himalayan", Checked = false },
new FormInputs { Id = 8, Name = "Cool Valley", Checked = false },
new FormInputs { Id = 9, Name = "Dew Drops", Checked = false },
new FormInputs { Id = 10, Name = "Dislaren", Checked = false },
};
MyViewModel mvm = new MyViewModel() { inputCollection = list, isList = true };
return this.View("Index", mvm);
}
[HttpPost]
public ActionResult CheckBoxPost(MyViewModel model)
{
var selected = model.inputCollection.Where(x => x.Checked).Select(x => x.Name);
//ViewBag.Values = String.Join(", ", list);
ViewBag.Values = selected;
MyViewModel mvm = new MyViewModel() { inputCollection = model.inputCollection, isList = true };
return this.View("Index", mvm);
}
The checkbox controller crashes with this error:
error: Model.input.passWord: Object reference not set to an instance of an object.
There are so many errors in your code. You will need to study a book or two about ASP.Net MVC. Otherwise, you will never end asking very simple questions, and finally get frustrated.
The following code will help you to keep going. Ideally, you want to keep GET and POST action method names to be same which is Index in this case, unless you have a valid reason.
The problem model.input is null is you did not instantiate it after post back.
// Remove Index, and rename PasswordInput to Index
public ActionResult Index()
{
FormInputs pss = new FormInputs();
// pss.passWord = password;
MyViewModel mvm = new MyViewModel { input = pss, isList = false };
return View(mvm);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
var selected = model.inputCollection.Where(x => x.Checked).Select(x => x.Name);
//ViewBag.Values = String.Join(", ", list);
ViewBag.Values = selected;
model.input = new FormInputs(); // <-- You need to instantiate FormInputs
model.inputCollection = model.inputCollection;
model.isList = true;
return View( model);
}
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;