Call Controller Method using Ajax request - c#

please your help to call a method from controller using ajax request, below is my code, but error had returned says that the source of controller cannot be found.
here is my ajax code
function GetServices() {
var e = document.getElementById("catagories");
var strUser = e.options[e.selectedIndex].value;
var id = e.options[e.selectedIndex].id;
$.ajax({
url: "~/VasController/ExecuteVas/",
//url: '<%= Url.Action("GetServices", "Vas") %>',
type: 'POST',
contentType: 'application/json',
data: {"id": id},
success: function (result) {
alert(result);
}
});
}
and here is my controller method
[WebMethod]
public static string GetServices(string id)
{
return id;
}
kindly advice, i am still beginner in c# and MVC

in your controller file
public class YourControllerNameController : Controller
{
[HttpPost]
public ActionResult Dosomething(int? id)
{
//your code
return View();
}
}
then in your view
$.post('#Url.Action("Dosomething","YourControllerName")', { id: id }, function (data) {
});

You have to do the following:
1- Decorate the Action method with [HttpPost] tag
2- Remove the word 'controller' for the Ajax URL it would be 'url: "~/Vas/ExecuteVas/"
3- if 1 and 2 did not work,Try putting the Ajax URL without ~/

Related

Why doesn't the value come to the method via AJAX?

I created an ASP.NET Core 6 MVC web application, code in Index.cshtml:
<button onclick="Get()">Send</button>
<script>
function Get(){
var results = new Array();
var emp1 = { "ID": "12", "Name": "Manas" };
var emp2 = { "ID": "2", "Name": "Tester" };
results.push(emp1);
results.push(emp2);
console.log(results);
$.ajax({
url: 'Home/GetQuiz',
data: JSON.stringify(results),
type: 'POST',
contentType: "application/json",
dataType: 'json',
success: function (resp) {
//request sent and response received.
}
});
}
</script>
HomeController:
[HttpPost]
public IActionResult GetQuiz(List<Employee> empList)
{
return RedirectToAction("Index","Home");
}
I get into the action of the controller, but the list is empty, please tell me why?
In the layout page, the link to the library is connected:
<script src="~/lib/jquery/dist/jquery.min.js"></script>
since you are using "application/json" content type, you should use frombody attribute in your action, and redirect is not working when ajax is used, try just to return action
public IActionResult GetQuiz([FromBody] List<Employee> empList)
{
return Index();
}
since your content type is "application/json", use the [FromBody] attribute in the controller action method. Read more on Microsoft docs.
And since you are on the Home controller already, you do not need to redirect to action, just return the index.
public IActionResult GetQuiz([FromBody] List<Employee> empList)
{
return Index();
}

how to fix this my following code is not working

I am trying to post a data and trying to return from controller to back again and show it to alert box but dont know why this is not working
here is the controller code
[HttpPost]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
and here is my front end code
<input id="projName" type="text" name="Name" required="" value="javascript">
and this is my script code
var projectname = document.getElementById('projName').value;
$.ajax({
url: '/Worksheet/getRequirmentsByProject',
type: 'post',
data: { projectname },
contentType: 'application/json; charset=utf-8',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
In your case, I am giving you a simple example on how you can POST your form variables to your controller using AJAX:
<script type="text/javascript">
var projectname = document.getElementById('projName').value;
var json = {
projectname: projectname
};
$.ajax({
url: '#Url.Action("getRequirmentsByProject", "Worksheet")',
type: 'post',
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
alert(data);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
And in your controller, you can get this value as:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult getRequirmentsByProject(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string projectname= jsondata["projectname"];
return Json(projectname);
}
its httpget and writing with a wrong way
[HttpGet]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
this is the right way thankyou for pointing out

MVC How to call an action in controller from view to return a value

I am working on an mvc project. In a Home controller i have an action which is called GetCityByID which takes id and checks the db for a city and returns city name.
In My View, I want to call this action and get a result and display it.
Can someone please demonstrate different ways of doing this?
i think i could through ajax/javascript, also through #url.Action ?
Yes, you can make ajax call to controller method from view. Following will be the JS code.
$.ajax({
async: false,
cache: false,
type: "GET",
url: "#(Url.Action("YourAction", "YourController"))",
data: { "id": ui.item.Id }, //Param
success: function (data) {
}
});
MVC code in controller.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ActionName(int id)
{
....Your Code....
return Json(model);
}
In View :
$.ajax({
async: false,
cache: false,
type: "GET",
url: "#(Url.Action("YourAction", "YourController"))",
data: { "id": ui.item.Id }, //Param
success: function (data) {
}
});
MVC Controller Code:
[HttpGet]
public JsonResult ddlSurgeryDescription(string id)
{
Do Process Here
return Json(new { id = ViewData["ddlSurgeryDescription"] }, JsonRequestBehavior.AllowGet);
}

In ASP.NET MVC3,can I get a JsonResult in View?

Suppose I have a Action which return a JsonResult. Like below code:
public ActionResult testAction()
{
return Json(new { name="mike",age="20"});
}
It json an anonymous object and return it. Then I want to write below code in View (.cshtml) file with razor engine.
#{
JsonResult m = ///some method can help me get the JsonResult
//Then I can print the value of m
#m.Data.ToString()
}
How to do it?
why do you use json result in view? You can:
public ActionResult testAction()
{
return View(new Model{ name="mike",age="20"});
}
In your View, you can call your testAction method via an Ajax call, then access to your returned object. But as far as I know, you must return a model.
Create a Model
public class YourModel
{
public string Name { get; set; }
public int Age { get; set; }
}
A Controller :
public ActionResult testAction(string name, int age)
{
YourModel ym = new YourModel();
ym.Name = name;
ym.Age = age;
return Json(ym, JsonRequestBehavior.AllowGet);
}
Your View :
var name = "Mike";
var age = "20";
$.ajax({
url : "#Url.Action("testAction", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({name: name, age: age})
}).done(function (data) {
alert(data); // Do what you want with your object, like data.Name
})
This is a dummy example because you pass parameter from the view to the controller, then send them back to the view, but I think this sample can help you to better understand how to play with Ajax call in ASP.NET MVC3. Ajax call is asynchronous, but thank to deferred .done, you wait for the end of the server call to ensure your data object is filled
You have to use ajax to read.
$.ajax({
url: "/YourController/testAction/",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: json,
type: 'POST',
success: function (data) {
setTimeout(function () {
//find your html element and show.
$("#ShowSomewhere").val(data.name);
}, 500);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
try use Html.Action("actionName");
this return a string

How to pass an object to a MVC controller via Jquery Ajax Get

I am new to jquery and I can't resolve the following problem : I want to pass an object to one of the controllers in my mvc application. Here is what I got so far:
function enterPressed() {
$(function () {
$('#textBox').keypress(function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
doSomethingElse(textBox.value)
}
});
});
}
function doSomethingElse(p) {
$.ajax({
type: 'GET',
data: {string: p},
url: '"Control/AddControl/Index"',
success: function (data) { alert(p) },
error: function (errorData) { alert("fail") }
});
return true;
But every time when I press enter I end up with the fail. My controller is found in ~/Controllers/Control/AddControl. Do any of you see the problem ?
My C# code:
public class AddControlController : Controller
{
//
// GET: /AddControl/
public ActionResult Index(string control)
{
return RedirectToAction("ShowControl");
}
}
You should change value name to control, as action expected. Also you can use #Url.Action() helper for setting url param.
$.ajax({
type: 'GET',
data: { control : p},
url: '#Url.Action("Index","AddControl")',
success: function (data) { alert(p) },
error: function (errorData) { alert("fail") }
});
Finally, your action can't return redirect action with ajax response.
If you want to make redirect after successful response, you can make it in client side.
There are a few problems:
1-you are using a wrong url. The correct url is '/AddControl/Index'.
2-Your code in your controller won't work, since you are using ajax. You should return Json and handle the redirect in the client side.
3-You should allow GET through ajax:
public ActionResult Index()
{
return Json("Ok", JsonRequestBehavior.AllowGet);
}
You might want to just POST in stead of GET.
function doSomethingElse(p) {
$.post(
'#Url.Action("Index", "AddControl")',
{
control: p
},
function (data) {
alert(data);
}
);
}
You should decorate your controller action with the HttpPost attribute:
[HttpPost]
public ActionResult Index(string control)
{
return Json("I received this: " + control);
}

Categories

Resources