I need to get the resource data on js file.
so I want to transfer the resource data from controler action to js file by ajax callback.
How to do this?
I'm working in asp.net mvc 5
I'm do it's so:
controller Action:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult GetCultureResource()
{
ResourceSet resourceSet =
Resources.Resources.ResourceManager.GetResourceSet(new System.Globalization.CultureInfo(cultureName), true, true);
var dicResource= resourceSet.Cast<DictionaryEntry>()
.ToDictionary(x => x.Key.ToString(),
x => x.Value.ToString());
var jsonString = JsonConvert.SerializeObject(dicResource);
return Json(new { resource = jsonString});
}
javascript fanction:
function SetCultureResource() {
$.ajax({
type: "POST",
url: "/ControllerName/GetCultureResource",
dataType: "json",
success: function (data) {
var obj = jQuery.parseJSON(data.resource);
//do somthing as this with Resource
//alert(Resource.BeforLogOut);
},
error: function (data) {
}
});
}
Related
I'm trying to implement file download functionality thru ajax call in MVC.
After calling of controller method i always have a "parseerror", can somebody explain me why?
my ajax:
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
$.ajax({
type: "POST",
url: "/File/FileDownload",
//contentType: false,
//processData: false,
//dataType: "json",
data: { fileId: id },
success: function (data) {
$('#uploadStatus').html("ok");
},
error: function (err) {
alert(err.statusText);
}
});
});
and controller:
[HttpPost]
public FileResult FileDownload(int? fileId)
{
FileDBEntities db = new FileDBEntities();
tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
return File(file.Data, file.ContentType, file.Name);
}
with simple download link in razor it works, but not with ajax.
What am I doing wrong here?
Why not simple use
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
window.location = window.location.origin + '/File/FileDownload?fileId=' + id;
});
[HttpGet]
public FileResult FileDownload(int? fileId)
I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",
I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.
I have a JS function:
$(document).on('click', '#submitForm', function (e) {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'bool',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
});
My action:
public ActionResult FileExist(string fileName)
{
bool result = true;
string path = Server.MapPath(TempPath) + fileName + ".xlsx"; //Path for the file
string[] Files = Directory.GetFiles(Server.MapPath(TempPath));
for (int i = 0; i < Files.Length; i++)
{
if (path == Files[i])
{
//The filename already exists
result = false;
}
}
return Json(new { returnvalue = result });
}
What am I doing wrong here? I'm trying to get the bool value from FileExist method, and if it's true stop the form from submitting (e.preventDefault)
There is no dataType: 'bool'. Please use dataType:'json' dataType:'text' to send the boolean values
In your case, it should be dataType:'json'
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'json',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
Then
[HttpPost]
public ActionResult FileExist(string fileName)
{
}
First, specify dataType: 'json' in your jquery ajax request:
$.ajax({
// <...>
dataType: 'json'
// <...>
});
If you would like to use HTTP GET:
public ActionResult FileExist(string fileName)
{
// <...>
return Json(model, JsonRequestBehavior.AllowGet);
}
You can use HTTP POST method:
[HttpPost] // Add this attribute.
public ActionResult FileExist(string fileName)
{
// <...>
return Json(model);
}
On top of your controller method, you have to put this annotation:
[HttpPost]
Add [HttpPost] to your controller,set dataType:'json' and set async:false in jquery ajax why do you need POST method. Just use GET method and add JsonRequestBehavior.AllowGet in your controller
put datatype asjson not bool ans also add [HttpPost] attribute on your action or other way is to put type:'GET'
The available data types in a service call are:
xml
html
script
json
jsonp
As per your code:
change the dataType to json as you are returning json from the server.
And by default the ActionResult will be using GET while in your ajax call you have specified POST.
So include [HttpPost] at the top of the method.
I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>