I have a drop down list that I want to render a partial view depending on what item is chosen. For this, I am using jquery and MVC 5. After having put breakpoints in my controller, my Url.Action() call doesn't seem to be getting there when I change the dropdown selection. I'm not sure I understand how to use route values correctly so that could be it. This is what I've got:
Relevant part of starting view
<div>
#if (role == "admin")
{
<p>Choose state to view:</p>
<select id="stateList">
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="IA">Iowa</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MD">Maryland</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="NC">North Carolina</option>
<option value="NE">Nebraska</option>
<option value="NJ">New Jersey</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="SC">South Carolina</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</select>
<div id="#partialPlaceHolder">
</div>
}
JQuery to get to controller
//Load partial view when an admin changes the state selection
$('#stateList').change(function () {
var selection = $(this).val();
var url = '#Url.Action("StateData", "Visualizations")' + '?StateID=' + selection;
//url ends up looking like this: /Visualizations/StateData?StateID=IA (or some other state abbreviation)
$("#partialPlaceHolder").load(url, function () {
console.log("it worked");
});
});
Model
public class VisualizationModels
{
public String StateID { get; set; }
}
Controller for generating partial view
public ActionResult StateData(string stateID)
{
VisualizationModels vm = new VisualizationModels();
vm.StateID = stateID;
return PartialView("_SpecificStateData", vm);
}
UPDATE
Oddly enough, if I use $.get instead of #Url.Action, I will actually hit the controller action, it just won't render the partial view now for some reason...
//Load partial view when an admin changes the state selection
$('#stateList').change(function () {
var selection = $(this).val();
var url = '/Visualizations/StateData?StateID=' + selection;
$.get(url, function (data) {
$('#partialPlaceHolder').html(data);
});
Cannot you use something like this
var url = '#Url.Action("StateData", "Visualizations", new { StateID = selection})'
instead of
var url = '#Url.Action("StateData", "Visualizations")' + '?StateID=' + selection;
and check if this is working. Because if your parameter would not be passed correctly. Your route handler will not able to map correct action method.
I figured it out... it's the stupidest, peskiest little issue. In my main view (at the top of my original post) I had typed the id of my div wrong...
Wrong:
<div id="#partialPlaceHolder"></div>
Right:
<div id="partialPlaceHolder"></div>
Everything is working as expected now. Final JS looks like this:
//Load partial view when an admin changes the state selection
$('#stateList').change(function () {
var selection = $(this).val();
var url = '#Url.Action("StateData", "Visualizations", new { StateID = "_state" })'.replace("_state", selection);
$("#partialPlaceHolder").load(url, function () {
console.log("it worked");
});
});
Related
I have a table in this format:
table format
And i try to get this result programmatically:
desired result
I'm using asp.net mvc with razor.
I know there is an example here but i couldnt adapt in my situation :(
May you give an example please?
ADDED my work:
I think i must get the records via json, am i wrong? and im not good at in json
<script type="text/javascript">
$('#ddl_Hours').multiselect();
</script>
<select id="ddl_Hours" multiple>
#foreach (myModel item in ((MultiSelectList)ViewBag.MyList).Items)
{
int dayID = 0;
if (dayID != item.DayID )
{
<optgroup label="#item.DayID ">
<option value="#item.HourID">#item.Name</option>
</optgroup>
}
dayID = item.DayID;
}
</select>
Controller:
var list = (from p in db.T_MYTABLE
select new MyModel { HourID = p.HourID ,
DayID = p.DayID,
Name = p.Name
}).ToList();
ViewBag.MyList= new MultiSelectList(list, !string.IsNullOrEmpty(selectedValue) ? selectedValue.Split(',').ToArray() : null);
For generating such a grouped multi select using the jQuery plugin, first you need to render the HTML markup for grouped options like below
<select id="ddl_Hours">
<optgroup label="4">
<option value="1">00.00</option>
<option value="2">01.00</option>
<option value="3">02.00</option>
<option value="4">03.00</option>
</optgroup>
<optgroup label="2">
<option value="5">04.00</option>
<option value="6">05.00</option>
<option value="7">06.0</option>
</optgroup>
<optgroup label="3">
<option value="8">07.00</option>
<option value="9">08.00</option>
</optgroup>
</select>
To generate the above markup in your view, you can create a list of item's in your action method with the Group property.
var list = db.T_MYTABLE.ToList();
//Create a list of Groups
var groups = list.Select(x => x.DayId)
.Select(f => new SelectListGroup() { Name = "Day " + f.ToString() }).ToList();
var groupedOptions = list.Select(x => new SelectListItem
{
Value = x.HourId.ToString(),
Text = x.Name,
Group = groups.FirstOrDefault(a => a.Name == "Day " + x.DayId.ToString())
}).ToList();
ViewBag.MyList = groupedOptions;
return View();
Assuming Name property of your entity is string type. If it is numeric type, use the ToString() method when setting the Text property value in the projection part of the above linq query (Text=x.Name.ToString())
Now in your razor view, you can use the Html.DropDownList helper method to render the SELECT element.
#Html.DropDownList("ddl_Hours", ViewBag.MyList as List<SelectListItem>)
or for the multi select
#Html.ListBox("ddl_Hours", ViewBag.MyList as List<SelectListItem>)
Now you can call your jQuery plugin to make it fancy. I would call it inside the document's ready event
$(function () {
$('#ddl_Hours').multiselect();
})
and Voila!
I'm trying to add the attribute selected to an option inside a select, something like: <option value="item" selected>item</option>, but in an strange event the text selected is deleted when rendering the page.
For example I have the following code:
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<option
value="#str"
#sel>
#str
</option>
}
</select>
In this if searchCode == str then the #sel is set as "selected" but the problem is that when the site is rendered the #sel attribute is not printed.
For example, it should print:
<select>
<option value="a">a</option>
<option value="b" selected>b</option>
<option value="c">c</option>
</select>
But instead it prints:
<select>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
If I change my code to this:
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<option
value="#str"
#sel>
#str - #sel
</option>
}
</select>
I'll get something like this:
<select>
<option value="a">a - </option>
<option value="b">b - selected</option>
<option value="c">c - </option>
</select>
So the attribute selected is correctly calculated but it's not printed as it should.
Any ideas on what's happening?
It appears to be a bug: https://github.com/aspnet/Mvc/issues/3733
What I did is to change option as !option.
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<!option
value="#str"
#sel>
#str - #sel
</!option>
}
</select>
1) create class for search criteria
public class SearchCriteria
{
public string searchCode { get; set; }
public List<string> results { get; set; }
}
2) add the default option before binding the list
var searchCriteriaObj = new SearchCriteria { searchCode = "bla bla bla" };
searchCriteriaObj.results = searchManager.getResults(searchCode);
searchCriteriaObj.results.Insert(0, " Nothing Selected");
3) bind the object by passing it (Controller) after getting the results.
ViewBag.criteria = searchCriteriaObject;
4) View page:
<select asp-for="ViewBag.criteria.searchCode"
asp-items="ViewBag.criteria.results">
</select>
I want to know how to put drop down list like this:
<div>
<label>Price Range</label>
<select>
<option value="1">min</option>
<option value="50000">50,000</option>
<option value="100000">100,000</option>
<option value="150000">150,000</option>
</select>
in the view , and read the selected parameter in the controller
tnx
There are many ways to make it work.
Its depend on your needs.
I am going to show you the simplest way to create it in the view itself
You can do it like this all inlined in your *.cshtml file like so:
#{
var loadListItems = new List<SelectListItem>();
loadListItems.Add(new SelectListItem { Text = "text1", Value = "value1", Selected = true });
loadListItems.Add(new SelectListItem { Text = "text2", Value = "value2" });
}
//Begin Form
#Html.DropDownList("ListKey",loadListItems);
//End Form
Will produce the result as follows:
<select name="ListKey">
<option value="value1">text1</option>
<option value="value2">text2</option>
</select>
And on submitting it on controller side you can get the values as follows:
ActionResult YourActionName(FormCollection collection){
var selectedValue = collection["ListKey"];
}
I'm new at programming in MVC, so I ran into this problem...
I have the following selectBox:
<select class="span5" id="selectBox">
<option>Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
How do I get the selected value into a model?
Start by creating your select list in a ViewModel:
public class whatever {
public List<SelectListItem> MonthList {get;set;}
public string SelectedMonth {get;set;}
public whatever()
{
MonthList = new List<SelectListItem>();
MonthList.Add(new SelectListItem{
Text = "January",
Value = "January"
});
}
}
Then in your view you can just use the drop down razor helper:
#Html.DropDownListFor(m => m.SelectedMonth, Model.MonthList)
When you submit your page the selected option will automatically get picked up.
In the case of a default value being used in an ASP MVC drown down list, I need the code to return all values or simply ignore that particular search criteria.
Below is the code I have in my View and Controller. Since the '%' does not seem to be working, is there another keyword/operator that will do the job?
View:
<form method="post">
<select name="Table" title="Table" style="font-size:8pt;">
<option value="%">--Table Name--</option>
<option value="AgentContEd">CE</option>
<option value="AgentProductTraining">PT</option>
</select>
<select name="IssueType" style="font-size:8pt;">
<option value="%">--Issue Type--</option>
<option value="W">Warning</option>
<option value="E">Error</option>
</select>
<select name="Status" style="font-size:8pt;">
<option value="%">--Status Type--</option>
<option value="O">Open</option>
<option value="U">Under Review</option>
</select>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" style="padding-top: 0px;" />
</form>
Controller:
public ViewResult Index(FormCollection dropDownSelection)
{
//security
//if (!Security.IsViewer(User)) return RedirectToAction("Message", "Home", new { id = 2 });
//if (ViewBag.Level == 0) return RedirectToAction("Message", "Home", new { id = 2 });
string table = dropDownSelection["Table"];
string issue = dropDownSelection["IssueType"];
string status = dropDownSelection["Status"];
var followUpItem = from follow in db.FollowUpItems
where follow.TableName.Equals(table) &&
follow.IssueType.Equals(issue) &&
follow.Status.Equals(status)
select follow;
return View(followUpItem.ToList());
}
You can use either SqlMethods.Like or simply the String.Contains method. (Keep in mind that String.Contains will be problematic if you retain the use of % or any other SQL wildcards.)
So, the three variations would look like:
var followUpItem = from follow in db.FollowUpItems
where SqlMethods.Like(follow.TableName, table) &&
follow.IssueType.Contains(issue) &&
follow.Status.Equals(status)
select follow;
I haven't compiled this, but I'm guessing you want something like:
public ViewResult Index(FormCollection dropDownSelection)
{
//security
//if (!Security.IsViewer(User)) return RedirectToAction("Message", "Home", new { id = 2 });
//if (ViewBag.Level == 0) return RedirectToAction("Message", "Home", new { id = 2 });
string table = dropDownSelection["Table"];
string issue = dropDownSelection["IssueType"];
string status = dropDownSelection["Status"];
var followUpItem = from follow in db.FollowUpItems
where (follow.TableName.Equals(table) || table.Equals("%")) &&
(follow.IssueType.Equals(issue) || issue.Equals("%")) &&
(follow.Status.Equals(status) || status.Equals("%"))
select follow;
return View(followUpItem.ToList());
}