asp.net mvc ajax send two parameters - c#

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.

Related

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

How to Receive Ajax Data values from Controller in asp mvc

using the following script, I am trying to access the variables being sent using data in the ajax function but I couldn't.
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '#Url.Action("UpdateOrder")', // to get the right path to controller from TableRoutes of Asp.Net MVC
dataType: "json", //to work with json format
type: "POST", //to do a post request
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false, //avoid caching results
data: { test: $(this).text() }, // here you can pass arguments to your request if you need
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
here is the action in the controller
public ActionResult UpdateOrder()
{
// some code
var test = Request.Form["test"];
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
I tried Request.Form["test"] but the value of it is null. how should I receive the objects of data?
Your ActionResult is GET And you have no input parameter for your ActionResult so either change those or see below:
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: /ControllerName/ActionName
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { test: comments },
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
Then within your controller:
public ActionResult UpdateOrder(string test)
{
// some code
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
Update
Remember if you want to use POST then action you are calling has to be [HttpPost] like:
[HttpPost]
public ActionResult Example()
When there is no HTTP above your ActionResult Then Its By Default Get.
The action method should be decorated with the [HttpPost] attribute. Have you used the debugger to ensure that you're actually calling in to that method?
You can always just define a view model in C# and then accept that as a parameter to your post method - Asp.MVC will parse the post data for you as long as the names of the values are the same as your model.
Have you marked your action method with [HttpPost] attribute. ?
This post helped me a lot. I did the GET but POST raise an Internal Server Error just with [HttpPost]:
[HttpPost]
public ActionResult SaveOrder(int id, string test, string test2)
So i had to set params data with JSON.stringify and it worked. My full ajax request for POST:
$.ajax({
url: "/Home/SaveOrder",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: JSON.stringify({ id:2, test: "test3", test2: "msj3" }),
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});

Why I can't send parameter to action method with ajax?

This code works without sending parameter:
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
data: { },
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});
However if I want to send a parameter to the GetFee action method it doesn't work anymore:
data: { bookname : 'book1' }
And I changed my action method to accept parameter:
[HttpPost]
public ActionResult GetFee(string bookname)
You indicated:
contentType: 'application/json; charset=utf-8',
so make sure that you respect what you claimed to be sending to the server:
data: JSON.stringify({ bookname : 'book1' })
On the other hand, if you get rid of this application/json content type in your request, jQuery will use application/x-www-form-urlencoded by default and then you can simply use this:
data: { bookname : 'book1' }
Since you are specifying the datatype 'json'. So you can send only json object in request. So you need to convert data in json format.
You can do by using the JSON.stringify() method. The JSON.stringify() method converts a JavaScript value to a JSON string.
JSON.stringify(value[, replacer[, space]])
If you don't want to use JSON datatype, you don't need to convert it.
Simply use:
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
type: "POST",
cache: false,
data: {
'bookname' : 'book1'
},
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});
As Darin Dimitrov had previously replied, you don't send your data in the format where you declare in the contentType.
In my opinion you can choose these two ways:
1.Send your parameter like a JSON string (look at Darin Dimitrov's answer) and add a [FromBody] before the input parameter, to clarify where you want to read this value.
[HttpPost]
public ActionResult GetFee([FromBody] string bookname)
2.Avoid specifying the contentType, and dataType in your ajax call, like this
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
type: "POST",
cache: false,
data: { bookname : 'book1' },
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});

ASP.NET MVC And Ajax Send Data

I trying send data to my controller. Controller sends all data to client correcly but from client to controller not..
My front code:
$(document).ready(function () {
$("#MessageSend").click(function () {
var serviceURL = '/User/Chat';
var model = {
Message: $("#Message").val()
}
$.ajax({
type: "POST",
url: serviceURL,
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});
And my controller, I have two versions - non of those versions works.
[HttpPost]
public IActionResult Chat(ChatMessage model)
{
Console.WriteLine(model.Message);
return Json("chamara");
}
and
[HttpPost]
public IActionResult Chat(string Message)
{
Console.WriteLine(Message);
return Json("chamara");
}
Thank you for help.
The JSON.stringify() method converts a JavaScript value to a JSON string, hence
You need to change the data in a way that the Json can "understand" it
for that change to
data: JSON.stringify(model)
for more information about it look Here
Looking at your code, seems you are trying to send a JSON to User controller but your controller is expecting a string (controller example 2).
Also, it is a good practice to create specific classes for binding events via jquery such as "js-messageSend". It will minimize the chance of your script breaking if you need to change the Message class for any reason in the future, but forget that you have an event on it.
Try this:
$(document).ready(function () {
$("#MessageSend").click(function () {
var messageText = $("#Message").val();
$.ajax({
type: "POST",
url: '/User/Chat',
data: { Message: messageText },
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});

ajax post data null in mvc3 controller method

One of my jquery ajax posts sends post data to my .NET MVC3 controller method, but at the controller method, the data shows up as null. I have many other ajax posts that use practically the same method body, and they all work fine, so I'm not sure what is happening.
Ajax post:
$.ajax({
url: '/Entity/Relate',
type: 'POST',
dataType: 'json',
contentType: 'applicaiton/json; charset=utf-8',
data: { primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId },
success: function (data)
{
//do stuff
},
error: function ()
{
// throw error
},
complete: function ()
{
//do more stuff
}
});
Controller method:
[HttpPost]
public int Relate(int primaryEntityId, int relatedEntityId)
{
return relationshipRepository.Add(primaryEntityId, relatedEntityId);
}
The problem is when I break on the Relate method, primaryEntityId and relatedEntityId are null, even though in the post data in Firebug, it shows that {primaryEntityId: 13, relatedEntityId: 486} have been posted to the method.
Any suggestions or ideas as to why the post looks good, but the controller isn't picking up the data?
but at the controller method, the data shows up as null
That's not possible because Int32 is a value type and value types in .NET cannot be null. You probably meant that they are assigned to the default value. Anyway.
The problem is related to the contentType parameter that you have set in your AJAX request. You need to remove it because you are not sending JSON but a standard application/x-www-form-urlencoded request:
$.ajax({
url: '/Entity/Relate',
type: 'POST',
dataType: 'json',
data: {
primaryEntityId: parseInt(entityParentId, 10),
relatedEntityId: _createdId
},
success: function (data)
{
//do stuff
},
error: function ()
{
// throw error
},
complete: function ()
{
//do more stuff
}
});
If you want to send a JSON request define a view model:
public class RelateViewModel
{
public int PrimaryEntityId { get; set; }
public int RelatedEntityId { get; set; }
}
then have your controller take this view model as argument:
[HttpPost]
public int Relate(RelateViewModel model)
{
return relationshipRepository.Add(model.PrimaryEntityId, model.RelatedEntityId);
}
and finally send a real JSON request (using the JSON.stringify method):
$.ajax({
url: '/Entity/Relate',
type: 'POST',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({
primaryEntityId: parseInt(entityParentId, 10),
relatedEntityId: _createdId
}),
success: function (data)
{
//do stuff
},
error: function ()
{
// throw error
},
complete: function ()
{
//do more stuff
}
});

Categories

Resources