mvc get list from method in controller - asp.net-mvc

I am new to MVC. I have one button that when clicked, opens a modal pop up (JQuery). In this modal I have 10 DropDownLists, and I create a specific key with all the selected values from those dropdowns. I also have another button that opens another modal. Here's where I get confused: I need to do a query that includes the key, and with this result, I need to fill a WebGrid in the second modal.
How can I do this? I've been thinking about one actionlink or a partial view, or calling a method in the controller that returns the list.

With ajax is easy, look:
$.ajax({
type: "POST", // type of request
url: "page.php", // page
dataType: 'JSON', // Format of send and response
data: { id: "2", name: "example" }, // data in JSON format
sucess: function(response) {
alert('The response was: ' + response); // All ok
},
error: function() {
alert('Connection expired!'); // Request failed
}
});

Related

Rails 6: AJAX data not reaching controller

I'm trying to make a pretty standard ajax call, this is my code:
// app/javascripts/packs/contacts.js
jQuery(() => {
$(".upload-contacts-button").on("click", (e) => {
e.preventDefault();
//...
$.ajax({
url: "/pre-parse-contacts",
type: "post",
data: { my_param: random_param },
success() {},
});
});
});
This is my route:
post 'pre-parse-contacts', to: 'contacts#pre_parse_contacts', as: 'pre_parse_contacts'
For some reason the data I send in the ajax request never reaches the controller, when I try to puts params in the controller action I get this result:
------- DEBUG --------
{"controller"=>"contacts", "action"=>"pre_parse_contacts"}
I'm sure the ajax call is made, even the js.erb view tries to render but I get errors due to I need the data I send in the ajax call. Why is this happening?
Sorry I found the answer to my issue, it seems I was trying to send an array of strings in the params of the ajax request, this is why it was never reaching the controller.
joining the array made the trick:
$.ajax({
url: "/pre-parse-contacts",
type: "post",
data: { my_param: random_param.join() },
success() {},
});

How to get the value of Dropdown on the specific field using ajax (mvc)

sorry for the bad title I cannot express the proper subject to my problem
since, I'm a newbie in MVC and ajax I have a problem
In view I prepared a dropdown where it list all the shoes name (Shoe Table), now the customer has to select it but the twist it must display the Shoesprice (Shoe Table) once it select a shoe name. the view code is given below
View:
#Html.DropDownListFor(x => x.shoename, new SelectList(Model.ShoesModel,"shoename","shoename"), "Select Shoes Name", new {id="myDrop",#class="form-control" })
I have the script when you select it the item, this particular syntax is working
Script:
$("#myDrop").change(function ()
{
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: $(this).val() },
success: function (data) {
//how can I declare a value to get the and return the price
}
});
}
But, i don't know how to create an ajax syntax (get the price according to shoe name), and set to a controller
thank you for help
Since you want to return single value only, just use data in AJAX success result to show returned price value:
Controller
[HttpPost]
public JsonResult GetShoesPrice(string shoesName)
{
var customerViewPrice = (from c in _SBC.Shoeses // Change the condition here
where c.shoename.Contains(shoesName)
select c.ShoesUnitPrice).FirstOrDefault(); // or SingleOrDefault() for one and only returned value
return Json(customerViewPrice);
}
View (jQuery)
$("#myDrop").change(function () {
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: value },
success: function (data) {
// set input element value which will be posted on form submit with DropDownListFor
$('#price').val(data);
}
});
}
Note that if you want to show list of ShoesUnitPrice from selected shoesName, you need to use $.each() loop to iterate returned array of price value.

AJAX call to MVC controller action

I am new to MVC programming.I am working on a simple POC application that displays/edits data from Database.
I have 2 views and 2 controllers. On one of them the JQuery AJAX call to MVC controller action method is working fine. But not on the other one (In here, the AJAX call is not triggering the Action method).
Can anyone had this situation before???
The JQuery code is below:
$('#ddlZones').change(function () {
var value = $('#ddlZones option:selected').val();
// alert(value); var status = $('#ddlStatus option:selected').val();
// alert(status); $('#lstResources').children().remove();
$('#lstBeds').children().remove();
$.ajax({ url: 'FillResources', type: 'POST',
data: JSON.stringify({ ZoneId: value }),
dataType: 'json', contentType: 'application/json',
success: function (result) {
for (var r in result) {
$('#lstResources').append('<option value="' + result[r].Value + '">' + result[r].Text + '</option>');
}
}
});
});
Thanks
Latha
Check the controller url is called or not,
Also in data parameter you can call it simply like { ZoneId: value } instead of
JSON.stringify({ ZoneId: value }),
At server side get this parameter by using $_POST if you are using PHP
in controller, also check in console that, you are getting json from server side or not.
$.ajax({ url: 'FillResources', type: 'POST',
data:{ ZoneId: value },
dataType: 'json', contentType: 'application/json',
success: function (result) {
for (var r in result) {
$('#lstResources').append('<option value="' + result[r].Value + '">' + result[r].Text + '</option>');
}
}
});
Please check the request and the response in the browser. You can use the inbuilt ones in IE/Chrome/FF(Firebug) or fiddler. It probably is just a routing issue if this is ASP.NET MVC.
Specifically, look for what your request url is and what is the HTTP response from the server.
It is always a good practice to specify both the controller and actions in the routing urls to avoid any such errors.
Another thing to check will be if the change function is actually being called? You can put a console.log before the ajax request to make sure that this is not the case.

global ajaxError event

i have a global ajaxError event in my base.master, something like this
$(document).ajaxError(function(event, request, settings,thrownError) {
$("#results").append( "<li>some error msg.</li>" );
});
but i dont want to use "#results". i want it to be dynamic. i want the function to always display the error msg in the update-target element. how can i find the UpdateTarget Id that was used from my ajax call in the error event? thanks.
using (Ajax.BeginForm("action", null,
new AjaxOptions {
UpdateTargetId = "results", <--find this element in my error event
LoadingElementId = "loading",
I am not familiar with ASP, but the ajaxError receives all settings that are passed to the ajax method in the aptly named settings variable.
So if you have an AJAX call like this:
$.ajax({
url: '/some/url.asp',
data: myData,
resultsEle: $('#myResults')
});
You can access resultsEle in the ajaxError like this:
$(document).ajaxError(function(event, request, settings, thrownError) {
settings.resultsEle.append( "<li>some error msg.</li>" );
});
Again, I am not familiar with the way you are calling the AJAX method in your ASP code, but my guess would be you can get to the element this way:
$(document).ajaxError(function(event, request, settings, thrownError) {
$('#'+settings.UpdateTargetId).append( "<li>some error msg.</li>" );
});

call action in controller from onclick method

I have a CheckBox like this
<td><%= Html.CheckBox("seleccionado", false, new { onclick = "SeleccionarItems();" })%></td>
Now, I want to call a specific action from my controller, and pass the value of checkBox How can I do that..
function SeleccionarItems() {
-- call method to controller and pass value
}
I would use jQuery to post to the controller:
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: 'POST',
url: controllerName + '/ActionName',
data: { 'checkValue': $('#seleccionado').val() },
dataType: 'json',
success: function (jsonData) {
//This function gets called after posting to the server
},
error: function () {
alert('Error!');
}
});
Here is a tutorial that explains the whole process: Link

Resources