I have an MVC JsonResult Method that accepts one string parameter:
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
With a jquery method calling the method:
//Fetch Destinations
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "{countryId:'" + countryId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
BindDestinationSelect(msg)
}
});
});
However, the JsonResult seems to only receive a null parameter. Even though Firebug is showing that a parameter is being passed:
JSON
countryId
"11"
Source
{countryId:'11'}
Any ideas? Thanks
I think the problem is in how you are actually passing the data, you are doing so as a string:
data: "{countryId:'" + countryId + "'}",
When in reality, you should be using a structure on the client side;
data: { countryId: countryId },
jQuery should be able to handle passing the id correctly then. As you are doing it now, it is trying to send JSON to the server, which is not what MVC is expecting, it's expecting a POST with name/value pairs.
You might also want to consider the jQuery Form Plugin, as it makes serializing your Javascript structures into POST data very easy.
Ah, after much searching I've discovered the reason why it fails.
Nothing to do with malformed JSON etc, but rather the fact that the controller method doesnt know what to expect if you try to pass it JSON values:
http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863
So in my case, I've just elected to pass it a single string value.
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "countryId=" + countryId,
success: function (msg) {
BindDestinationSelect(msg.Data)
}
});
Here I suggest you to decorate your action with HttpPost attribute
Like :-
[HttpPost]
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
public JsonResult BindAllData(string Userid)
{
List<VoteList> list = new List<VoteList>();
var indexlist = db.TB_WebSites.ToList();
int i = 0;
var countlist = db.Tb_Votes.ToList();
var VCountList = db.Tb_Votes.ToList();
foreach (TB_WebSites vt in indexlist)
{
bool voted = false;
}
return Json(new { List = _list });
}
function DataBind() {
$("#LoadingDatas").show();
var userid = $("#FBUserId").text();
//alert('Data : ' + userid);
var InnerHtml = "";
$.ajax(
{
url: '/Gitex/BindAllData/',
type: 'POST',
data: { "Userid": userid },
dataType: 'json',
async: true,
success: function (data) {
//alert('Done');
//alert(data.List.length);
for (var i = 0; i < data.List.length; i++) {
});
}
Try this, it worked for me
jQuery function
success :function(Destinations)
Related
Purpose: The code written is suppose to save all the contents using Json and re direct to action.
Problem:
The current redirect using Json does not allow the redirection as suppose.
return new JsonResult { Data = new { status = status } };
The code is below for reference: Looking for suggestions:
View Code
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
window.location.href = d.Url;
//clear form
t = [];
d = [];
r = [];
$('#SN').val('');
$('#SA').val('');
$('#t').empty();
$('#d').empty();
$('#r').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
});
Controller
public JsonResult Save(SAVM O,)
{
bool status = false;
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
status = true;
}
else
{
status = false
}
return new JsonResult { Data = new { status = status } };
}
Here want to redirect like this:
return RedirectToAction("F", "SA");
but using JsonResult
Solution
View
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
window.location.href = d.Url;
})
} });
Controller
public JsonResult Save(SAVM O,)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
return Json(new { Url = "F/SA" });
}
You have a couple of options here, you decide which one you prefer based on your requirements.
Do not use AJAX. AJAX requests are meant for data required for the current page. You should use a synchronous request for the redirection.
Return the URL to which the client should redirect on the success event:
return Json(new { url = "/F/SA" });
And then:
success: function (d)
{
window.location.url = d.url;
}
Return the already rendered View and load it to the current page:
return View("some view...");
And then:
success: function (d)
{
$("#someElement").html(d);
}
I am relatively new in MVC and C#, and i am having a lot of problems to learn some little things. I am having some errors and would like any help to solve my problem.
I have these 2 models:
UsuarioDal:
public Usuario LoginById(int Id)
{
var login = (from u in db.Usuario
where u.IdUsuario == Id && u.Ativo == true
select u).FirstOrDefault();
return login;
}
UsuarioDeviceDal:
public UsuarioDevice getByUUID(string uuid)
{
var usuariodevice = (from c in db.UsuarioDevice
where c.UuId == uuid
select c).FirstOrDefault();
return usuariodevice;
}
Controller:
public HttpResponseMessage GetConsultaLogUsu(string uuid){
UsuarioDeviceDAL dev = new UsuarioDeviceDAL();
UsuarioDAL obj = new UsuarioDAL();
var device = dev.getByUUID(uuid);
var usu obj.LoginById(device.IdUsuario); // this is the line that i would like to work.
if (device != null){
return new HttpResponseMessage(){
Content = new StringContent("L")
};
}else{
return new HttpResponseMessage(){
Content = new StringContent("D")
};
}
}
Ajax:
function fn_verificalog() {
var uuid = $("#uuid").val();
$.ajax({
type: "GET",
url: linkServidor + "api/GuardaUsuario/GetConsultaLogUsu?uuid="+uuid,
contentType: "application/json",
success: function (data) {
navigator.notification.alert(data, fn_ErroApp(), "Sucesso teste.");
if (data === 'L') {
window.location.href = "verdelandia.html";
}
},
error: function () {
navigator.notification.alert("Estamos verificando o problema.", fn_ErroApp(), "Ocorreu um problema.");
}
});
}
If someone have any idea of how to solve that, i would stay really grateful. Thank you everyone with try to help.
I did couple things in your ajax configuration:
Removed contentType: "application/json" because you sending only query string. By default contentType is application/x-www-form-urlencoded; charset=UTF-8.
Instead to manually configure query string parameter I added as data option.
I added parameters in error handler and you will be able to inspect which error you have.
Please see how it looks in your case:
$.ajax({
type: "GET",
url: linkServidor + "api/GuardaUsuario/GetConsultaLogUsu",
data: {
'uuid': uuid
},
success: function(data) {
navigator.notification.alert(data, fn_ErroApp(), "Sucesso teste.");
if (data === 'L') {
window.location.href = "verdelandia.html";
}
},
error: function(xhr, ajaxOptions, thrownError) {
navigator.notification.alert("Estamos verificando o problema.", fn_ErroApp(), "Ocorreu um problema.");
}
});
Instead to creating URL as string you can try to use action helper:
#Url.Action("actionName", "controllerName", new { uuid= "<uuid>" })
I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...
I have a model I am trying to pass in from my view to my controller via an Ajax call which stringifies both the model and another string of data like this:
SetBinConfig: function (model, range) {
var _model = JSON.stringify(model);
var rangeSplit = range.split(/[ -]+/);
var _rangeSplit = JSON.stringify(rangeSplit);
var data = "model=" +_model + "&rangeSplit=" + _rangeSplit;
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/SetBinConfiguration',
type: 'POST',
data: "{'data' : '" + data + "'}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
if (data.error == 1) {
cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
}
},
error: function (x, h, r) {
console.log(x, h, r);
}
});
},
Which is then received by this method:
public ActionResult SetBinConfiguration(string data)
{
string range = data.Split(new string[] { "&rangeSplit=" }, StringSplitOptions.RemoveEmptyEntries)[1];
string tempModelData = data.Split(new string[] {"&rangeSplit="}, StringSplitOptions.RemoveEmptyEntries)[0];
string modelData = tempModelData.Replace("model=", "");
DefaultConfigurationModel model = new JavaScriptSerializer().Deserialize<DefaultConfigurationModel>(modelData);
string[] rangeSplit = Regex.Split(range, " - ");
foreach (IdentifiBINConfiguration ibc in model.IdentifiBINConfigs)
{
if (ibc.LowerRange == rangeSplit[0] && ibc.UpperRange == rangeSplit[1])
{
model.IdentifiBINConfiguration = ibc;
return Json(new { error = 0 });
}
}
return Json(new { error = 1 });
}
However, I get this error:
The value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" is not of type "IdentifiMessenger.Implementations.Identifi.Object.IdentifiBINConfiguration" and cannot be used in this generic collection. Parameter name: value
And I don't know what that means at all. I know what the Dictionary is, but why can I not just deserialize this object? I followed other answers right here on SO and I don't understand why this isn't working.
Edit:
Model is quite literally my model, sent from my JS like this:
IdentifiConfig.SetBinConfig(#Html.Raw(Json.Encode(Model)), $('#BinRangesHidden').val());
And range is just a value from a hidden. I'm not posting back my model because I just need to modify one value and then have the page pull that modified value down later.
You still have to serialize your data.
data: JSON.stringify(data),
Then in your controller, your object should auto-parse:
public ActionResult SetBinConfiguration(MyData data)
Alternatively, you can parse it manually:
public ActionResult SetBinConfiguration(string data)
{
MyData resumeDto = JsonConvert.DeserializeObject<MyData>(data);
...
How can I pass an array of strings to a controller in asp.net mvc4?
Here is my code
jQuery:
function FnSaveAnalyses(){
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
alert(checked); // it shows all the records without problem
var url = urlBiologieDemande + "Save";
$.post(
url,
data = { values: checked},
traditional= true,
success = function (data) {
DataSaved();
});
}
Controller
public ActionResult save(string[] values)
{
//Traitement
}
When debugging, I get null values.
POST IT AS JSON array.
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
var url = urlBiologieDemande + "Save";
$.ajax({
type: 'Post',
dataType: 'json',
url: url ,
data: JSON.stringify(values:checked),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
}
});
then get the JSON in the Controller
and Parse it ..
see this