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();
}
Related
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
Why TestData does not receive anything?
POST http://localhost:46628/Home/TestData 500 (Internal Server Error)
index.cshtml:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/knockout-2.2.0.js"></script>
<button data-bind="click: sendata">send data</button>
<script>
function MyViewModel() {
var self = this;
self.sendata = function () {
$.ajax({
type: 'POST',
url: 'Home/TestData',
contentType: 'application/json; charset=utf-8',
data: { json: 'json', date: 'date' },
dataType: 'json'
});
}
}
ko.applyBindings(new MyViewModel());
</script>
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public void TestData(string json,string date)
{
Console.WriteLine(json);
}
}
You use parameter data like this:
data: { json: 'json', date: 'date' },
Even though you specified that your content type is json, jQuery uses $.param to serialize your data, so instead of sending the json the data is sent like this:
json=json&date=date
Your server though expects json to be provided, so model binding fails.
Instead you should manually serialize the data to json before making AJAX call:
data: JSON.stringify({ json: 'json', date: 'date' }),
The rest of the code seems to be fine.
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 ~/
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);
}
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);
}