I'm currently working on an ASP.Net MVC project.
I have a JavaScript function which takes an XML string as input. I would like to send this to the controller.
I have done so using an AJAX request, but in the controller the string is null.
View:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")'
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: xml,
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public ActionResult Save(string xml)
{
Console.WriteLine(xml);
W6ViewModel viewModel = new W6ViewModel();
viewModel.engineers = db.W6ENGINEERS.ToList();
viewModel.tasks = db.W6TASKS.ToList();
viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
var engList = new List<object>();
foreach (var engineer in viewModel.engineers)
{
engList.Add(new { key = engineer.ID, label = engineer.Name });
}
ViewBag.engineers = engList;
return View("Index", viewModel);
}
var xml = scheduler.toXML()
alert(xml):
Error Code (Sorry, wall of text):
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client (xmlString="<data><event>
Name your parameter like this:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")';
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: { xml: xml},
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Also put this tag above you controller action:
[ValidateInput(false)]
See the following ajax call:
$.ajax({
url: '#Url.Content("~/myaccount/CheckDuplicateEmailAddress")',
data: { "emailAddress": email },
async: false,
type: "post",
success: success,
error: error
});
And controller action is below. you need to send param as this:
data: { "emailAddress": email }
Remember case sensitivity and double quotes:
public bool CheckDuplicateEmailAddress(string emailAddress)
{
}
Related
I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
I have a webapi method defined like the following in a controller:
[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing
public object VerifyResourceURL([FromBody]string url, int resourceID)
When I call it with jquery ajax the variable url is always null, why?
(resourceID has the correct value)
$.ajax({
url: '/api/resources/15/VerifyUrl',
type: "POST",
async: true,
dataType: "json",
data: { url: 'some-url-to-verify' },
success: function (data) {
if (data.Exist === false) {
urlIsValid = true;
}
else {
alert('URL already exist');
urlIsValid = false;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus, "Error: " + errorThrown);
}
});
You're sending an object with a url property, but expecting the body to be a string.
Try changing datatype and data as such:
dataType: "text",
data: 'some-url-to-verify',
I have sample code and you can try something like this
//JavaScript
var command = {
url: $("#txtOrigin").val()
};
$.ajax({
type: "POST",
url: "/api/booking",
contentType: "application/json",
data: JSON.stringify(command),
dataType: "text",
success: Created,
error: Failed
});
//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{
}
fromBody does not work in Web mvc Core 2.2 for Post
In Postman I am trying to post some data. I have made it as simple as possible;
iam see error 400 Bad Request
var UserVmodl =
{
In_User_Name:'',
In_Family :$("#Family").val(),
User_Name :$("#Name").val()
In_National_Code :$("#National_Code").val(),
In_Birth_Date_sh :$("#dateBirth_Date").val(),
In_Email:$("#Email").val()
}
$.ajax({
url: '#Url.Action("SaveUser", "PersonalInfo")',
type: 'POST',
data: JSON.stringify(UserVmodl ),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
beforeSend: function (request) {
sendRequestVerificationToken(request);
},
success: function (data) { localSuccess(data); onSuccessFunc(data); }
});
[Route("PersonalInfo")]
[Area("client")]
public class PersonalInfoController : Controller
{
[HttpPost]
[Route("save")]
public IActionResult SaveUser([FromBody] PersonalInfo UserVmodl)
{
//var Result= _IUserService.UpdateUser(UserVmodl);
return View();
}
}
Try to send RequestVerificationToken from headers if you need yo add antiforgery validation.
$.ajax({
url: '#Url.Action("SaveUser", "PersonalInfo")',
type: 'POST',
headers : {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(UserVmodl),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (data) { localSuccess(data); onSuccessFunc(data); }
});
Remember to add #Html.AntiForgeryToken() in your form.
Besides,you need to return a json result since your ajax needs a return type of json.
I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
In my MVC3 app, I'm using $.ajax to call a method of type JsonResult to get data to be displayed:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: "/Documents/GetDocumentData",
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});
This is my Action:
[HttpPost]
public JsonResult GetDocumentData(string id)
{
//my code
return Json(new { success = true});
}
When im debugging on my development machine, it works fine. I deployed it to my test web server and i get '404 page not found dev/testwebsite/Documents/GetDocumentData' I should get this when debugging if something was wrong, but i dont. Why am I getting this error? Thanks
Your URL in the javascript is wrong, if that dev/testwebsite/Documents/GetDocumentData is the URL on the server.
You should be using #Url.Action() to automatically form those URLs in the cshtml page.
Example:
#Url.Action("actionName","controllerName" )
So, for your specific case, it would be:
#Url.Action( "GetDocumentData", "Documents" )
In the javascript, it would look like this:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: '#Url.Action("GetDocumentData","Documents")',
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});