I have a drop down list
<select onchange="alert(this.value);">
<option selected="selected" value="cat">cat</option>
<option value="dog">dog</option>
</select>
I would like to make it so that when the users changes a value then an AJAX call is sent to my MVC controller which then updates the database.
I've done this with forms but never from javascript. Does anyone have an example of how this could be done.
thanks,
If you are using jQuery:
<select id="category" name="category">
<option selected="selected" value="cat">cat</option>
<option value="dog">dog</option>
</select>
and then:
$(function() {
$('#category').change(function() {
$.post('/home/save', { selectedCategory: $(this).val() }, function(result) {
alert('success');
});
});
});
which will send an AJAX request to the following action:
[HttpPost]
public ActionResult Save(string selectedCategory)
{
// TODO: process the selected category
return Json(new { success = true });
}
Related
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");
});
});
<select id="TypeOfUser" name="typeOfUser" class="active text-normal">
<option value="2" onclick="location.href='#(Url.Action("Index", "User", new { typeOfUser = 2}))'">CMS Users</option>
<option value="3" onclick="location.href='#(Url.Action("Index", "User", new { typeOfUser = 3}))'">Site Users</option>
</select>
on selection of dropdown item I want to call my action method with selected value-
public async Task<IActionResult> Index([FromQuery] int typeOfUser = 2)
{
SearchUsersResponse searchUserResponse = await new SearchUsersHandler(_db).Handle(new SearchUsersCommandAsync
{
Type = typeOfUser
});
return View("Index", searchUserResponse);
}
Currently on dropdown selection change I am not able to call action method.
onclick won't work on the option. What you can do is execute your javascript code for redirecting on the onchange event of the SELECT element.
<select id="TypeOfUser" name="typeOfUser" class="active text-normal"
onchange="doIt(this,'#Url.Action("Index", "User")')">
<option value="2" >CMS Users</option>
<option value="3">Site Users</option>
</select>
Assuming you have a javascript method which has 2 parameters. The first parameter is a reference to the SELECT element on which the onchange event occurred. So you can access the value property to get the selected option's value.
function doIt(item,baseUrl) {
window.location.href = baseUrl + '?typeOfUser=' + item.value;
}
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"];
}
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());
}
I have some app on asp.net mvc.
And I am trying to create table filter. Page is very difficult, so i can't get data from JSON response. I am trying to get it via call action with params.
function refresh() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, null, "json");
}
<select id="list" onchange="refresh()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<%foreach (var i in (IEnumerable<int>)ViewData["list"])
{ %>
<%=i %><br />
<%} %>
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
ViewData["list"] = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
return View();
}
But I don't see new data. What's wrong?
How I can refresh page?
PS I meen that i wanna go(redirect) from action A to action A(with param). I don't want reconstruct page on client side
You aren't doing anything with the result you retrieve with the get call. Also, since you're returning a view, you should set your data type to html.
$.get('/Home/Index', params, function(html) {
$('body').html(html);
},'html');
I'd note that I would probably only replace the section that gets updated. You can do this by using a partial view to hold just that section, then when you get the request via AJAX you can return just the partial view instead of the full view. The other thing that I would do is make the views strongly-typed to IEnumerable<int> and pass a model, instead of using view data.
View
<script type="text/javascript">
$(function() {
$('#list').change( function() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, function(html) {
$('#listResults').replaceWith(html)
}, "html");
});
});
</script>
<select id="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<% Html.RenderPartial( "ListResults" ); %>
Partial View
<div id="listResults">
<%foreach (var i in Model)
{ %>
<%=i %><br />
<%} %>
</div>
Action
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
var model = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
if (this.Request.IsAjaxRequest())
{
return PartialView(model);
}
return View(model);
}
I see one problem in the code above:
The $.get() does not do anything when your request is complete(your data has been fetched from the server)
Instead of passing null there you should pass in a function with a parameter which is the data. Example:
$.get("/Home/Index"
, params,
function(data){
//do something with data.
//data is json object returned
}, "json");
in this function you can actually have your filter applied to the table