I can't seem to understand how to update a div of items after a category is selected. I've got this far and am now confused. How to get the values from the view into the controller to make the query?
//get <li> clicked and display the items in that category
$(document).ready(function() {
$('#test li').click(function() {
var selector = "input[name='" + $(this).id + "value']";
var catID = $(selector).val();
$.ajax({
url: "...",
type: "get",
data: {//return all the item info},
success: function(data) {
//update div contents here?
}
});
});
});
Partial to be updated upon which category is clicked
#foreach (var item in Model)
{
<ul>
<li>#item.item_name</li>
<li><input type="hidden" class="item_id" value="#item.ID" /></li>
</ul>
}
Controller
public ActionResult PartialTwo( int id)//how to pass category id?
{
var query = from d in db.Items
where d.catId==id
orderby d.dateAdded
select d;
var results = query;
return PartialView("_FullInfoPartial", results);
//returns items in the clicked category
}
instead of two li
<li>#item.item_name</li>
<li><input type="hidden" class="item_id" value="#item.ID" /></li>
you can just use one in order to decrease dom size if it is not required
<li data-id="#item.ID">#item.item_name</li>
and you can get the partial view result with $.get easily
$("#test li").on("click",function(){
var requestPage = "/PartialTwo?id=" + $(this).data("id");
$.get(requestPage, function(result){
$("#content").html(result); // where you want to put the result
});
});
I've answered a very similar question over here, though the example was using PHP. The basic idea is the same however. your MVC4 will return some data type that will be turned into HTML (the easiest way is to just return straight HTML) and then you will append this HTML value to a DOM element (in this case, the div item of your choice).
the JQuery would look similar too:
var request = $.ajax({
type: "POST",
url: "example.php",
data: data_obj,
dataType: "html"
}).done(function(msg) {
$("#example_element").append(msg);
}
Attempting to load a "div" as dynamic content is returned
Use Ajax.BeginForm as follows,
#using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "youDivId" }))
Using the above and making your controller returning Patial View will update your div with the partial view result.
Related
My project required auto-suggestion in when user input their query in the input field. I have tried to implement using materialize CSS, Ajax, Django, Jquery as follows:
HTML PAGE:
<div class="row" id ="adddiv">
<div class="input-field col s3">
<input placeholder="Stock Item" type="text" name="StockItem-1" class="validate dropdown-trigger" data-target="dropdown1" id="stockitem">
<ul id="dropdown1" class="dropdown-content">
</ul>
</div>
JS Snippet:
$(function(){
// $("#stockitem").change(function(){
$('.dropdown-trigger').keyup(function(){
$('.dropdown-content').html("")
var query = $('.dropdown-trigger').val();
var data = {'query':query}
var url = 'auto_suggest'
$.ajax({
type: "GET",
url: url,
dataType : 'json',
data: data,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
success: function(data)
{
var results = data["resultlist"]
$.each(results, function(index,value){
$('.dropdown-content').append("<li>"+ value +"</li>");
});
}
});
});
});
I am able to get the data from backend and li elements are appending with selected ul elements, but it's not displaying as dropdown in front-end.
Refer materialize CSS dropdown:
I suspect the problem with CSS please here
You shouldn't be using the drop down for that, you should be using the autocomplete
https://materializecss.com/autocomplete.html
Also remember to call the Initialization functions as that's what it looks like you are currently missing. With the below modifications it should work. But again, you should be using the autocomplete for this.
$(function(){
///////////////////////////////////////////////
// YOU HAVE TO INITIALIZE THE DROPDOWN
const dropDownEl = $('.dropdown-trigger')[0]
M.Dropdown.init(dropDownEl)
///////////////////////////////////////////////////
// $("#stockitem").change(function(){
$('.dropdown-trigger').keyup(function(){
$('.dropdown-content').html("")
var query = $('.dropdown-trigger').val();
var data = {'query':query}
var url = 'auto_suggest'
$.ajax({
type: "GET",
url: url,
dataType : 'json',
data: data,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
success: function(data)
{
var results = data["resultlist"]
$.each(results, function(index,value){
$('.dropdown-content').append("<li>"+ value +"</li>");
});
///////////////////////////////////////////////
// YOU HAVE TO OPEN THE DROPDOWN
M.Dropdown.getInstance(dropDownEl).open();
///////////////////////////////////////////////////
}
});
});
});
I am new to jQuery and I am trying to iterate through a list of strings after making an ajax call to a controller. In this controller, I am returning a list of strings and I want to iterate over this list in jquery and present it to the screen. Here is my code.
This is my controller
[HttpPost]
public ActionResult GetComments() {
var cmts = ex.GetComments(psts, psons);
var lstCmt = ex.GetCommentsList(cments, psons);
return Json(lstCmt);
}
This is my view:
<div>
<button id="ldBtn" class="btn btn-primary">Load</button>
</div>
<div id="cments">
</div>
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
type: "POST",
dataType: "html",
url: '#Url.Action("GetComments")',
data: {},
success: function(lists) {
//Something needs to be fixed here
$.each(lists, function(i, name) {
$('#comments').append('<p>' + name.Value + '</p>');
});
}
});
});
});
</script>
When I return the list, I am getting a huge string. How do I fix this?
Thanks in Advance
There's a couple of issues in your JS code. Firstly you're telling jQuery to expect a HTML response in the dataType setting. This is why you see the response as a string. This should be changed to JSON instead, that way jQuery will deserialise the response for you.
Secondly you're attempting to concatenate a Value property on each item in the list, yet they are strings (as you state you're returning a List<string> from your action), and will not have that property. You can simply append the name itself. Try this:
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
url: '#Url.Action("GetComments")',
type: "POST",
dataType: 'json',
success: function(comments) {
$('#cments').append('<p>' + comments.join('</p><p>') + '</p>');
}
});
});
I assume the #comments/#cments discrepancy is only due to amending parts of your code when creating the question.
Also note that I simplified the append() logic so that it appends all comments in a single call, which should be slightly faster.
I am new to asp.net mvc and I am facing this issue with dropdownlist now.
Sorry if I am asking a stupid question.
I have a main View AbcView which is bound to a Controller AbcController which passes an AbcModel to the view.
I have 2 partial views inside this AbcView which are loaded on button clicks.
Inside the second partial view, I have this code :
#Html.DropDownListFor(model => Model.TrajectoryName, new SelectList(#Model.Trajectories, "Value", "Text"),
new { #class = "dropdown-leftandright", id = drpTrajectory" })
Inside the first partial view, I have some data which is being added to database on some button click like this :
function deleteAction(trajID) {
$.ajax({
type: "POST",
url: "/AbcView/DeleteAction",
data: JSON.stringify({ deleteTraj: trajID }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// I want to update the drpTrajectory dropdownlist here
},
error: function (e) {
return "error";
}
});
}
My issue is I want to access the drpTrajectory in second partial view inside this function. I want to add some item to this particular drop down list.
I tried to access the dropdownlist by using $('#drpTrajectory') and tried to add an item. But it is failing.
I tried to add data like this
$('#drpTrajectory ').add(val(data.x).text(data.y));
data will be a member from a IEnumerable<SomeClass> dataList and SomeClass contains id and name which could be the value and text respectively.
I am already updating the model data during the button click ie #Model.Trajectories is getting updated.
So please help me to add an item to this dropdownlist which is in second partial view from my first partial view without refreshing the entire view.
Any idea?
Assuming your method is returning a collection of objects, then to create and append an option to a <select> you need
var select = $('#drpTrajectory') // cache it
$.ajax({
type: "POST",
url: '#Url.Action("DeleteAction", "AbcView")',
data: { deleteTraj: trajID },
dataType: "json",
success: function (data) {
select.empty() // if you need to remove the existing options
$.each(data, function (index, item) {
// Create an option element
var option = $('<option></option>').val(item.id).text(item.name);
// append it to the select element
select.append(option);
})
},
....
});
Side notes
Always use #Url.Action() to ensure that your url's are correctly
generated
There is no need to stringify() the data and then add the
contentType` option
Your controller method should be returning a collection of anonymous
objects containing just the 2 properties you need (there is no point
sending back extra data that's not use)
var data = dataList.Select(x => new { id = x.id, name = x.name });
return Json(data)
Your use of new SelectList(#Model.Trajectories, "Value", "Text")
suggests that the property Trajectories is already
IEnumerable<SelectListItem>. If that is the case, there is no
point creating an identical SelectList from the original one, so
just use
#Html.DropDownListFor(model => Model.TrajectoryName, Model.Trajectories, new { #class = "dropdown-leftandright", id = drpTrajectory" })
The DropDownListFor() method is already creating
id="TrajectoryName" so there is no real need to overwrite it by
using new { id = drpTrajectory" }
Here is your solution:
success: function (data) {
// I want to update the drpTrajectory dropdownlist here
$.each(data, function (i, item) {
$('#drpTrajectory').append($('<option>', {
value: item.id,
text : item.name
}));
});
}
I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)
<a class="" href="/LaborerSearchByName/Index">
<img src="/Content/images/b7.png" id="b7"
onclick="bb7();"
onmouseover="bigImg(this)"
onmouseout="normalImg(this)">
</a>
The call for action link
#Html.Action("Menu", "MenuItem", new { id = "MenuId"})
"MenuId" must by a dynamic value based on which button is clicked.
Here goes my solution, use Html.ActionLink() -
#Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { #id = "MenuId" })
Then say you have image control like this -
<img src="/Content/images/b7.png" id="b7"/>
Then you have simple JQuery script to replace query string in this way -
<script>
$(document).ready(function () {
$("#b7").click(function () {
$("#MenuId").attr("href","/MenuItem/Menu/" + this.id);
});
});
</script>
In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7
UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
public JsonResult GetJson(string MenuId)
{
List<string> urls = new List<string>();
urls.Add("https://google.com");
urls.Add("https://bing.com");
return Json(urls, JsonRequestBehavior.AllowGet);
}
Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.MenuId = $("#Menu").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {ou parse data
// This is how we parse returned json string
$.each(data, function (i, item) {
alert(data[i]);
});
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
When you run the code, you should see following view -
When you enter the value and click on anchor tag -
And as a result, you will get all the results parsed -
You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}
I'm scratching my head how to combine results of 2 jQuery ajax calls which return the results into the same DOM element. Here is my setup:
there are 2 calls: one from a list of foods and second from a list of ingredients
both calls return a list of ingredients
the idea is to make a shopping list (ingredients to buy) based on 2 sources (list of foods and list of ingredients)
user can create shopping list either by selecting foods (ingredients are retrieved from the database) or he can select ingredients directly from a list of ingredients
Problem: these 2 calls are working fine each on its own. But the problem is that result from one call is always replacing the result from the second call and vice-versa.
var postUrl = "http://localhost:8000/ingredients/";
var ingrUrl = "http://localhost:8000/ingrs/";
var selectedFoods = [];
var selectedIngrs = [];
$('.foods a').click(function(event){
clickedLink = $(this).attr('id');
if (selectedFoods.indexOf(clickedLink) != -1) {
var index = selectedFoods.indexOf(clickedLink);
selectedFoods.splice(index, 1);}
else {
selectedFoods.push(clickedLink);
};
var jsonFoods = JSON.stringify(selectedFoods);
$.ajax({
url: postUrl,
type: 'POST',
data: jsonFoods,
dataType: 'html',
success: function(result){
$('.ingredients').html(result);
}
});
});
$('.ingr-list a').click(function(event) {
clickedIngr = $(this).attr('id');
if (selectedIngrs.indexOf(clickedIngr) != -1) {
var index = selectedIngrs.indexOf(clickedIngr);
selectedIngrs.splice(index, 1);}
else {
selectedIngrs.push(clickedIngr);
};
var jsonIngrs = JSON.stringify(selectedIngrs);
$.ajax({
url: ingrUrl,
type: 'POST',
data: jsonIngrs,
dataType: 'html',
success: function(result){
$('.ingredients').html(result);
}
});
});
I tried to play around with this line $('.ingredients').html(result); using append instead of html but that won't work because the user should be able to take ingredients off the list (see the if conditions in both functions).
Just use different containers for them
<div class="ingredients">
<div id="first"></div>
<div id="second"></diV>
</div>
Then set the .html() of $("#first") and $("#second") instead of .ingredients
Use .append
$('.ingredients').append(result);
see if this is the answer underscore js template
what you need to do is not passing html back, but passing json back, and using js template to render it at the browser.
some fake code:
var global_ingredients = [];
var list = "<% _.each(ingredients, function(ingredient) \
{ %> <li><%= ingredient.name %></li> <% }); %>;";
$.post('', postdata, function(ingredients){
global_ingredients.push(ingredients);
// here you could also eliminate duplicated ingredients,
// sort the ingredients, do whatever you likes
var new_html = _.template(list, global_ingredients);
$('.ingredients').html(new_html);
});