selectedValue from view to controller MVC - asp.net-mvc

Filter records in index view using dropdown list . How replace xxxxxxx with selectedValue from dropdownlist to filter. I am not sure how to select the selectedValue from dropdown list in the view. The controller code and the view code is below. I know its a small problem. But I am trying to find for some hours.The filter is working fine if i replace with xxxxxx with 1 , 2 etc.But I want to change xxxxx with selectedValue from Dropdown list.
controller code
ViewBag.doctorsid = new SelectList(db.doctors, "doctorsid", "doctorsname",selectedValue);
return View(appointments.Where(d => d.doctorsid == xxxxxxx).ToList());
view code
#Html.DropDownList("Doctorsid","Select Doctor")

Use script given bellow
Script
$("#Doctorsid").change(function () {
var doctorsid = $('#Doctorsid').val();
var url = "/ControllerNmae/ActionResultName/+doctorsid ;
window.location.href = url;
});

Use a Model with variables for list and drop down value instead of passing list directly to view
Controller:
ViewBag.ClientTypeID = new SelectList(db.ClientType.Where(ct => ct.IsDeleted != true), "ID", "ClientTypeName");
View:
#Html.DropDownListFor(m => m.ClientTypeID, new SelectList(ViewBag.ClientTypeList, "Value", "Text"), new { #class="drop"})

Related

mvc controlling two dropdownlist to filter data

hello everyone I want to ask a question abuout mvc dropdownlist. I am trying to filter the datas to their places or their codes while dropdowns selected index changed. I can do it when I use one dropdown but when I use more than one dropdown I cannot get the results separately.
As you see in the picture I have two dropdownlist.
public ActionResult Index(int? id,int? ddwList)
{
Repository<Order> _ro = new Repository<Order>();
IEnumerable<SelectListItem> _orderSelectListItem = _ro.All().AsEnumerable().Select(s => new SelectListItem
{
Text = s.code,
Value = s.id.ToString()
});
ViewData["ddOrder"] = _orderSelectListItem;
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<SelectListItem> _workshopSelectListItem = _rw.All().AsEnumerable().Select(s => new SelectListItem
{
Text = s.name,
Value = s.id.ToString()
});
ViewData["ddwList"] = _workshopSelectListItem;
Repository<ClothShipment> _rcs = new Repository<ClothShipment>();
IEnumerable<MyClothShipment> _myClothShipment = null;
if (id != null)
{
int? idOrd = _rcs.Find(w => w.orderId == id).orderId;
//int? idWork = _rcs.Find(w => w.workshopId == id).workshopId;
if (idOrd != null)
{
_myClothShipment = _rcs.All().Where(w => w.orderId == id).Select(s => new MyClothShipment
{
id = s.id,
amount = s.amount,
orderName = s.order.code,
clothName = s.clothList.name,
workshopName = s.workshop.name,
shipDate = s.shipDate
});
}
//else if(idWork != null){
// _myClothShipment = _rcs.All().Where(w => w.workshopId == id).Select(s => new MyClothShipment
// {
// id = s.id,
// amount = s.amount,
// orderName = s.order.code,
// clothName = s.clothList.name,
// workshopName = s.workshop.name,
// shipDate = s.shipDate
// });
//}
}
else {
_myClothShipment = _rcs.All().Select(s => new MyClothShipment
{
id = s.id,
amount = s.amount,
orderName = s.order.code,
clothName = s.clothList.name,
workshopName = s.workshop.name,
shipDate = s.shipDate
});
}
return View(_myClothShipment);
}
my view is here
<div id="sample_editable_2_length" class="dataTables_length">
<label>
#Html.DropDownList("ddwList",(IEnumerable<SelectListItem>)ViewData["ddwList"],"Atölye Seçiniz",new {#id="StateDropDown1", #class = "span15 chosen"})
</label>
</div>
my view is here
<div id="sample_editable_2_length" class="dataTables_length">
<label>
#Html.DropDownList("ddwList",(IEnumerable<SelectListItem>)ViewData["ddwList"],"Atölye Seçiniz",new {#id="StateDropDown1", #class = "span15 chosen"})
</label>
</div>
<div id="sample_editable_1_length" class="dataTables_length">
<label>
#*<select class="m-wrap small" name="sample_editable_1_length" size="1" aria-controls="sample_editable_1">
</select>*#
#Html.DropDownList("ddOrder",(IEnumerable<SelectListItem>)ViewData["ddOrder"],"Sipariş Kodu Seçiniz",new {#id="StateDropDown", #class = "span15 chosen"})
</label>
</div>
and here is my script code
$("#StateDropDown").change(function (e) {
var controllerName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var actionName = '#ViewContext.RouteData.Values["Action"].ToString()';
var _id = $("#StateDropDown").val();
var _url = "/" + controllerName + "/" + actionName + "/" + _id;
window.location.href =_url
});
$("#StateDropDown1").change(function (e) {
var controllerName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var actionName = '#ViewContext.RouteData.Values["Action"].ToString()';
var _id = $("#StateDropDown1").val();
var _url = "/" + controllerName + "/" + actionName + "/" + _id;
window.location.href = _url
});
I am filling the dropdowns when on page load from database and getting all the data to show with dropdowns I want to filter the data that shown... And with this code one of my dropdown works I am taking the id of selected item (Index(int? id)) in here but when I try to use both of them separately it doesnt work how can I make both of them work. What should I do ? The second parameter always comes null or if I use different parameter except "id" it is again coming null ? and also I tried to take parameter as string but it also came null... Thank you for your helps.
To explain what your code is doing:
When your select a value from your first select, you are passing its value to the Index method (e.g. /Index/1) so the value of parameter id is 1 but no value has been passed to parameter ddwList so it is null. When you select a value from the second select you are passing its value to the index method (e.d. /Index/5) so the value of parameter id is 5 but no value has been passed to parameter ddwList so again it is null.
Assuming you want to display a table based on the selections of both selects, then you need to construct the url as /Index?id=1&ddwList=5. Therefore, remove the change events from your selects and add a button that constructs the query in its click event. However, the way you are doing this is reloading the whole page each time. I suggest you consider loading the table from a partial view using a jQuery.get() method to avoid a complete page load each time. For example
public ActionResult Index()
{
// Build the 2 select lists only
return View();
}
Index view
// Add the two #Html.DropdownFor()...
<button id="LoadTable">Load Table</button>
<div id="TablePlaceholder"></div>
and the script
$('#LoadTable').click(function() {
var id1 = // the value of the first select
var id2 = // the value of your second select
$.get('#Url.Action("Table")', { id: id1, ddwList: id2 }, function(data) {
$('#TablePlaceHolder').html(data);
});
}
and the partial result
public ActionResult Table(int? id, int? ddwList)
{
// Build your table view based on values of id and ddwList
return PartialView();
}
If I understand this, you are able to use one of the drop downs at a time and that drop down successfully sends it's value to your controller while the other drop down always sends null. If that's the case, that is working correctly with the way you made your dropdownlists with an option label.
As explained in the msdn documentation:http://msdn.microsoft.com/en-us/library/dd492256(v=vs.118).aspx
optionLabel Type: System.String The text for a default empty item.
This parameter can be null.
So if you want both of the drop down lists to be usable at the same time, you'll need to remove the events for .change and add a form with those dropdowns AND a submit button within to use both values at the same time.
OR
Do not use an option label meaning the first option of the dropDownList will be used as it's initial/default value. Here is a link to the msdn docs showing the different ways to format the Html.DropDownList helper: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlist(v=vs.118).aspx
I hope I understood you correctly!

Dropdownlist in MVC 4

I am trying to use simple dropdownlist in my edit form, where user can correct information, with help of dropdownlist.
So I use this:
public ActionResult Edit(string zonesList)
{
using (var dbVn = new userDbEntities())
{
...
var zList = new List<string>();
var zQuery = from d in dbVn.TimeZoneTables // take data for List from table
select d.TimeZone;
zoneList.AddRange(zQuery.Distinct());
ViewBag.zonesList = new SelectList(zList);
}
}
And in View I put this code:
Zones: #Html.DropDownList("zonesList")
My question is, how in View use this:
#Html.DropDownList("zonesList")
on this code
#Html.EditorFor(model => model.TimeZoneId)
Thanks for any idea.
Use jquery or javascript as below:
#Html.DropDownList("zonelist", new SelectList(ViewBag.zonesList,<value>,<text>),"Select Vendor/customer",new{ #class = "form-control",required = "required",#id="zone" })
Now want to change editor for value
#Html.EditorFor(model=>model.TimezoneId,new{#id="time"})
Jquery code for above
<script type="text/JavaScript">
$(document).ready(function () {
$("#zone").change(function(){
var t =$("#zone").val();
if(t==/*somevalue*/)
{
//set value for time id
//like $("#time").val(/*new val*/)
}
});
});
</script>
As I am using Time Zones I find cool solution that works only for time zones. First I actualy don't need table with time zones saved, but simple in my View I call library of .Net timezones:
#Html.DropDownListFor(o =>o.TimeZoneId, TimeZoneInfo.GetSystemTimeZones().Select(o => new SelectListItem{Text = o.DisplayName, Value = o.Id}))

accessing viewbag in the view

net MVC. I have assigned a list of objects to the viewbag property can anyone please tell me as to how i can get the list in the view to use it in the drop down list? here is my controller code & view code
Controller:
public ActionResult GetSection(int sectionId,int contactId)
{
ContactDetailSectionModel contactDetailSection = new ContactDetailSectionModel { SectionId = sectionId,ContactId=contactId };
contactDetailSection.FetchAllSubsections();
ContactDetailSectionModel customSections = new ContactDetailSectionModel();
customSections.FetchCustomSubSections();
if(customSections != null && customSections.ContactDetailSubSections != null)
{
ViewBag.CustomSubSections = customSections.ContactDetailSubSections;
}
return PartialView("~/Views/Contacts/Details/EditSection.cshtml", contactDetailSection);
}
View Code:
#Html.DropDownListFor(m => m.ContactDetailSubSections[1], new SelectList(ViewBag.CustomSubSections , "Name", "Name",Model.ContactDetailSubSections[1].Name))
#Html.TextAreaFor(m => m.ContactDetailSubSections[1].Text)
I think the first parameter in your #Html.DropDownlist should be string or some scalar quantity it cannot be a collection.

Should I send select list data to the view or let it get the data itself?

I have a create method in my controller and this opens up a view. On the view the user can enter data to populate the model. Some of that data comes from select lists. These select lists are populated from the database.
What I would like to know is should I:
a) Get data for the select lists in the controller, populate a field like this:
public IEnumerable<SelectListItem> Statuses { get { return GetStatusType(); } }
pass Statuses to the model and then do a for () to loop through statuses and create a select list and options HTML
b) Do nothing in the controller and in the view have the following in the model:
<select id="Q_StatusID" name="Q.StatusID">#Html.Raw(
SelectHelper.Status(false, #Model.PageMeta.StatusID))</select>
Where the SelectHelper is C# code that gets all the select list and options HTML.
c) Some better way:
I would go with the first one. some thing like this
a helper method
public List<SelectListItem> getAllSelectList(List<Items> lists)
{
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (Term term in lists)
{
selectListItems.Add(new SelectListItem() { Text = term.yourselectfield, Value = term.your value });
}
return selectListItems;
}
on your controller
//assuming you GetStatusType() method will return list of objects
ViewData.selectlist=getAllSelectList(GetStatusType());
on your view, if you are using Razor
#Html.DropDownList("selectlist", null, "Choose")
or
<%: Html.DropDownList("selectlist", null, "Choose") %>
Create a static Look-up class & static method for your GetStatusType there.
Cache all the status types after first time loading from your database.
Call GetAllStatusType from the view to display.
I would create a view model, which has a IEnumerable< Statuses > property. Then in your view to display the select element :
#Html.DropDownListFor(model => model.PageMeta.StatusID, new SelectList(Model.Statuses, "Id", "Name"), "Some default which has no value")
Where Id and Name are set to the appropriate properties in your Statuses model.

ASP.NET MVC dropdown with a default empty option

Is there a way to include a default empty option (or with text) if there is no selected value for a dropdownlist?
The below will prepend string.Empty to the SelectList (or IEnumerable) specified in the ViewData["Menu"] item. The select will have id and name MenuID.
<%= Html.DropDownList( "MenuID",
(IEnumerable<SelectListItem>)ViewData["Menu"],
string.Empty ) %>
Documentation: DropDownList method
For Example:
Controller :
private void InitScreenInfoCollate()
{
IEnumerable<MstBrd> listbrd = ibrandRepository.GetItemsByUsercode("");
ViewBag.Brands = new SelectList(listbrd, "brd_cod", "brd_mei", null);
}
View :
#Html.DropDownList("Brands", null, string.Empty, new { #class = "form-control"})
Result :
This easy solution worked for my mvc5 project:
in view:
#{
Model.ModelItemsList.Add(new ModelItem{ });
SelectList modelItemSelectList = new SelectList(Model.ModelItemsList, "ModelItemID", "ModelItemName");
}
Just add a new item to the List<> you want to display in your view.
In my case, I added a empty "ModelItem" to my List<ModelItem> ModelItemList. Since my ModelItemID is a Guid, I had to check for Guid.Empty in my controller method and do some code.
Thats all.
The solution presented here worked very well for me: http://forums.asp.net/t/1142484.aspx/1
The basic idea is that you set the AppendDataBoundItems property of your DropDownList to true and then put an asp:ListItem in the DropDownList and that will become your default item with all the databound items coming after it.

Resources