i am trying to pass in a filename as a requestparameter into a controller, but it returns with an invalid request?
$(document).ready(function (event) {
$('#btnTask').click(function () {
$.ajax({
url: "/Home/Sometask/",
data: "c:\\somefile.txt",
async: false,
success: function (data) { alert(data); }
});
event.preventDefault;
});
});
public string Sometask(string id)
{
return "ready";
}
Use data: { filename: "c:\\somefile.txt" }
You have to give a variable name for the post data so your controller know how to map the value.
Related
I have a button sending an input from a text field in a form to my mvc controller using ajax. I now want the controller to return 2 strings as a json, and fill those strings into html inputs.
Controller
[HttpPost]
public ActionResult getName(string Name)
{
string SecondString = "secondString";
return Json(Name, SecondString);
}
View
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
$('#FirstTextFieldToFill').val(result);
$('#SecondTextFieldToFill').val(result);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
You're wrongly assigned parameters to the Json() method to return response of JsonResult, because the second parameter is JsonRequestBehavior or contentType. You should return Controller.Json() response with single parameter like this:
[HttpPost]
public ActionResult GetName(string Name)
{
string SecondString = "secondString";
return Json(new { Name = Name, SecondString = SecondString });
}
And then modify your AJAX call to return 2 strings from response by using property names:
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("GetName", "Home"),
data: { Name: $("#txtName").val() },
success: function (result) {
$('#FirstTextFieldToFill').val(result.Name);
$('#SecondTextFieldToFill').val(result.SecondString);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
Worked like this:
Controller
[HttpPost]
public ActionResult getName(string Name)
{
string SecondString = "secondString";
return Json(new { Name, SecondString });
}
View
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
$('#FirstTextFieldToFill').val(result.Name);
$('#SecondTextFieldToFill').val(result.SecondString);
$('#SecondTextFieldToFill').show();
$('#FirstTextFieldToFill').show();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
For this you should create a class having two string eg.
public class example
{
public string FirstString {get; set;}
public string SecondString {get; set;}
}
create object of the class in the controller and add the strings to it serialize to json and return
[HttpPost]
public ActionResult getName(string Name)
{
example eg=new example();
eg.FirstString ="your first string";
eg.SecondString ="your second string";
string jsonString= JsonConvert.SerializeObject(eg);
return Json(jsonString);
}
JS file should extract the strings from the json object
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
var jsonResult=JSON.parse( result );
$('#FirstTextFieldToFill').val(jsonResult.FirstString);
$('#SecondTextFieldToFill').val(jsonResult.SecondString);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
Dependency required in controller are
JsonConvert is from the namespace Newtonsoft.Json
Use NuGet to download the package
"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install"
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');
}
});
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');
}
});
});
I am trying to pass the data of the view model to one js method and from there I need to pass the VM to another controller method to show the data.
here is what I have did:
$(document).ready(function () {
var content = GetHomeContent('/Home/CastContent');
if (content) {
saveBDContent('/Message/Details/', content);
}
});
function GetHomeContent(url) {
var modelData;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
contentType: 'application/json',
success: function (data) {
if (data) {
modelData = data;
}
},
error: function (data) {
status = false;
}
})
return modelData;
};
function saveBDContent(url, data) {
var status = false;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
if (data == "200") {
status = true;
}
},
error: function (data) {
status = false;
}
})
return status;
};
The problem am facing is , the content I retrived from the method show the namespace of the ViewModel. When I pass that to the new controlled the Viewmodel content is coming null.
Do I need to add anything to get/Pass the proper content ?
The Dummy method skeleton
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM);
}
I have missed out the JsonRequestBehavior.AllowGet in my controller method, I have added and the results are coming perfectly.
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM,JsonRequestBehavior.AllowGet);
}
and also I have set the HTTP status as post in the jquery method
Do something like that in the Controller:
public JsonResult QuickSave(BookEntry bookEntry) {
YourViewModel model = new YourViewModel();
return Json(model);
}
EDIT >> The associated Javascript code is :
$.ajax({
type: "POST",
url: 'The URL',
data: 'The JSON data',
dataType: "json",
success: function (theViewModel) {
// Do some JS stuff with your model
},
error: function (xhr, status, error) {
// Do some error stuff
}
});
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data)
}
});
});
I am using the ajax call above to get a model back how would i use the model object in the success function. As in I need to be able to use the data like a views model like #model.Type lets say. how could i do that with the json data in the success?
The data object contains the properties passed down via the server.
You can then access them like:
var name = data.Name;
var testData = data.TestData;
Your Action could look like:
public JsonResult LeadCounts()
{
return Json(new { name = "Darren", testData = "Testing" });
}
In MVC3 you could do it like this:
public ActionResult LeadCounts()
{
var data = new { Count = 1, Something = "Something" };
return Json(data, JsonRequestBehavior.AllowGet);
}
In view:
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data.Count);
}
});
});