I know this has been asked a lot of times. But believe me I have tried them and this ain't working.
I have this simple List and Method :-
$scope.TblData = [];
var Name='Name'; var Desc='Desc';
$scope.TblData = [
{ Key: Name, Value: ClassSubjectName },
{ Key: Desc, Value: ClassSubjectDesc }
];
InsertFactory.InsertClassSubject($scope.TblData).then(function (d) {
alert(d.data + ' Subject Details');
}, function (error) {
alert('Cannot Save Contact Details');
})
Which I'm getting at factory like :-
BoardObj.InsertClassSubject = function (TblData) {
var ViewID = 'ClassSubject';
var Data = $.param({ TblList: ViewID, TblData: TblData });
return $http({
method: 'POST',
url: '/Admin/InsertTblData',
data: JSON.stringify(Data),
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
}
});
}
Trying to get it at server like this:-
if (Request.Form["TblData"] != null)
{
JsonData = Request.Form["TblData"].ToString();
}
aBundleInsert.TblDataParams = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(JsonData);
Ofcourse I'm doing it wrong but can't find the issue.
You are not posting your data as form post.
TblData is a scope variable, it will not come inside your Form object, Form is meant for input elements only.
Ideally you should be posting the data to a model at the server side, but if you still want to access it on server side, you can try like following.
string postContent = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (var reader = new StreamReader(Request.InputStream,
System.Text.Encoding.UTF8, true, 4096, true))
{
if (HttpContext.Current.Request.ContentLength > 0)
{
postContent = reader.ReadToEnd();
}
}
Related
I am getting some string data along with files & i can access file like this Request.Files[0] but question is how can i access value of string objects? I am already trying to access it like this: Request.Form["url"] but seems not returns appropriate data. Please tell me how can i access Request.Form["url"] in a proper way.
Jquery Payload:
//FormData
var formData = new FormData();
$(".wholeBar").each(function (key, value) {
var findFiles = $(this).find(".hpicFile"); //find the element
var file = findFiles[0].files[0]; //get the actual file object
formData.append('files[]', file); //append all files to formData
// console.log(value);
var urlInput = $(this).find(".hurl");
formData.set("url", urlInput);
console.log(urlInput.val());
});
//Ajax request
$.ajax({
url: "/Controller/Upload",
type: "POST",
processData: false,
contentType: false,
data: formData, //Send form Data
success: function (response) {
console.log(response)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
C#:
var ddd = Request.Files[0];
var fff = Request.Form["url"];
//foreach (var item in fff)
//{
// var aaa = item.ToString();
//}
return Json("ok");
You can set string Data in below format in Jquery
var formData = new FormData();
var obj = {
Username: "user5",
Email: "em#example.com"
};
formData.set("data", obj);
and Receive it on Controller side as below format
VB.Net
Dim objUser As cls_User = JsonConvert.DeserializeObject(Of cls_User )(Request("obj"))
C#
cls_User objUser = JsonConvert.DeserializeObject<cls_User>(Request("obj"));
You need to create a class to capture the data coming from FormData() and then use the same object to retrieve it from (Request("obj") to Dim objUser As cls_User
I'm trying to use AJAX and calling web method like this in my code.
function generate_source(year_source, month_source) {
var gData_source = '';
if (year_source) {
gData_source = [];
gData_source[0] = year_source;
gData_source[1] = month_source;
console.log('first part');
}
else {
var d_source = new Date();
gData_source = [];
gData_source[0] = d_source.getFullYear();
gData_source[1] = d_source.getMonth() + 1;
console.log('second part');
}
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
var ctx = document.getElementById("order_source").getContext('2d');
$.ajax({
url: "dashboard.aspx/getordersource",
data: jsonData_source,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#loader_divsource").show();
},
success: function (response) {
$("#loader_divsource").hide();
var chartLabel = eval(response.d[0]); //Labels
var chartData = eval(response.d[1]); //Data
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: chartLabel,
datasets: [
{
type: 'doughnut',
label: chartLabel,
data: chartData,
backgroundColor: [
"#FF6384",
"#36A2EB",
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
]
}
]
}
});
}
});
}
var d_source = new Date();
gData_source = [];
$('#year_source').val(d.getFullYear());
$('#month_source').val(d.getMonth() + 1);
generate_source('', '');
My web method is like this;
[System.Web.Services.WebMethod]
public static List<string> getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
var returnData = new List<string>();
......
return returnData;
}
Whenever I try to run this data, my breakpoint for the web method is not hit. Further, if i use the same method without data, i don't get this error. It's driving me crazy.
I think your problem is in this code :
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
you are trying to serialize array with key value pair that it is become invalid.
change to this :
var jsonData_source = JSON.stringify(gData_source);
also your web method should be like this :
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.JSON)]
// just return a string, not list, your JSON string should have contain all your enumerable in your string Data
public static string getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
JsonSerializer serializer = new JsonSerializer();
var returnData = serializer.serialize(ds);
......
return returnData;
}
Hope it helps.
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'm trying to implement a simple WebMethod in C# to search a db of 50,000 people. I'm using Twitter Bootstrap bloodhound.js and typeahead.js to tokenize and autocomplete the responses.
When I run this code, typeahead shows a dropdown menu with undefined.
How can I correctly process the JSON response to strip out the d object returned by .NET WebMethod and correctly pass my records to Bloodhound? I've tried this using the dataFilter method provided by jQuery's $.ajax, but it's not working for me.
C# WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object searchStaffByName(string q)
{
using (App_Data.DQDBDataContext dc = new App_Data.DQDBDataContext())
{
var results = dc.getStaffDetails(q).ToList();
return new { Status = "OK", Records = results, Count = results.Count };
}
}
Typeahead JS implementation:
var textlookup = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.val);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'Search.aspx/searchStaffByName',
replace: function (url, query) {
searchQuery = query;
return url;
},
ajax: {
beforeSend: function (jqXhr, settings) {
settings.data = JSON.stringify({
q: searchQuery
});
jqXhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
},
dataFilter: function (data, type) {
if (type === "json") {
data = $.parseJSON(data);
if (typeof data.d === 'object' && data.d.Count > 0) {
return data.d.Records;
}
}
},
type: 'POST'
}
}
});
textlookup.initialize();
$('.autocomplete').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'textlookup',
displayKey: 'Forename',
source: textlookup.ttAdapter()
});
Sample JSON Response:
{
"d": {
"Status":"OK",
"Records": [{
"id":45711192,
"phone":"514-579-5721",
"Forename":"Jayden",
"Surname":"Adams",
"DOB":"\/Date(990226800000)\/"
},
{
"id":12603644,
"phone":"333-143-9094",
"Forename":"Jake",
"Surname":"Adams",
"DOB":"\/Date(43542000000)\/"
},
{
"id":68196438,
"phone":"440-505-2403",
"Forename":"Josh",
"Surname":"Adams",
"DOB":"\/Date(-51152400000)\/"
}],
"Count":6
}
}
If your typeahead data will be in the name: 'textlookup', array, populate the array with your JSON response first. The following assumes data is the JSON.
textlookup = [];
for (var i = 0; i < data.d.Records.length; i += 1) {
textlookup.push(data.d.Records[i].Forename);
}
This should push each Forename into the array textlookup. You are getting the undefined error because you are placing objects into the array.
I spent some time on this and found that it's better to return a an string array.
Here's my web method.
[WebMethod]
public static string[] MemberLookup(string MbrFullName)
{
DataSet ds = (dataset provider goes here)
List<string> members = new List<string>();
foreach(DataRow dr in ds.Tables[0].Rows)
{ members.Add(string.Format("{0}-{1}", dr["label"].ToString(), dr["value"].ToString())); }
return members.ToArray();
}
I am wanting to pass a dictionary of type <int,int> to my controller via an Ajax post.
The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.
Also in the post I have to pass in some other data, such as Id and name, which all works as normal.
How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?
Edit 2:
I have decided to just solve this with a post for each value instead of trying to pass a dictionary.
EDIT:
Here is my source for the function so you can see what I am trying:
function BindAddMenuItem() {
$(".AddMenuItem").click(function (e) {
e.preventDefault();
//get header id from link by removing addmenuitem from this.id
var currentId = $(this).attr("id").replace("AddMenuItem", "");
//get itemnumber, itemname, itemdetails from textboxes with same header id
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
var itemName = jQuery.trim($("#ItemName" + currentId).val());
var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());
var costs = new Object();
//select all textboxes with class "Header" + currentId
$(".Header" + currentId).each(function (i) {
var optionId = $(this).attr("id").replace("Option", "");
costs[optionId] = $(this).val();
});
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuItem",
data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
var newNum = parseInt(itemNumber) + 1;
$("#ItemNumber" + currentId).val(newNum);
BindAllBehaviours();
}
});
});
}
Something like (javascript)
dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;
$.post('/client.mvc/mypostaction/', { myDictionary: dict });
You can then post the dict object to your controller using a Dictionary<int, int> as property type.
ActionResult MyPostAction(Dictionary<string, int> myDictionary)
edit from author's code second time:
The following works for me, when having a Dictionary<string, int> kvPairs. <int, int> isn't going to work after all.
Make your post like:
var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;
$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); });
JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue> is expected. Example:
If you have a dictionary like this:
public Dictionary<string, decimal?> SomeMapping { get; set; }
then you have to use something like this in your JavaScript:
var sourceMapping = { a: 1, b: 1.5, c: null };
var SomeMapping = [];
for (var key in sourceMapping) {
if (sourceMapping.hasOwnProperty(key)) {
SomeMapping.push({ Key: key, Value: sourceMapping[key] });
}
}
I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json' (this may or may not be important in your case).
Client (JavaScript):
var dict = new Object();
dict.Key1 = "Value1"
dict.Key2 = "Value2"
$.post('/YourController/YourAction/', dict);
NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.
Server:
public ActionResult YourAction()
{
string postData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
postData = sr.ReadToEnd();
}
//Load post data into JObject (Newtonsoft.Json)
JObject o = JObject.Parse(postData);
//Extract each key/val
string val1 = (string)o["Key1"];
//Do whatever....
}
None of these worked for me except for mczers, but he doesn't show all the steps, and makes it difficult when you're trying to remember how you set up an ajax request. So I wanted to put everything that actually just works. First, in JavaScript:
var validDict = new Array();
validDict[0] = { key: 1, value: 4 }
validDict[1] = { key: 42, value: 5}
var path = "#Url.Action("ControllerName", "ActionName")";
$.ajax({
url: path,
type: "POST",
data: JSON.stringify(validDict),
contentType: "application/json; charset=utf-8",
async:false,
success: function(status, xhr)
{
alert(status);
},
error: function(xhr, status, error)
{
alert(error);
}});
Then in your controller:
[HttpPost]
public ActionResult ActionName(Dictionary<int, int> validDict)
{
// doStuff();
return Content("Success");
}
A dictionary of the kind IDictionary<string, string> on server side can be posted from javascript like
{"Key1": "Value1", "Key2": "Value2"}
on the Server Side in ASP.NET Web API
[HttpPost]
public IHttpActionResult([FromBody]IDictionary<string, string> requestParam){
}
Above example is for an Http POST with the Json data in the Body
For passing a Dictionary I found the following working answer:
submitting-a-dictionary-to-an-asp-net-mvc-action
#model WebApplication3.Controllers.ExampleViewModel #{ ViewBag.Title = "New";
var first = Guid.NewGuid(); var second = Guid.NewGuid(); }
<h2>New</h2>
#using (Html.BeginForm(new { action = "create", controller = "home" })) {
foreach (var kvp in Model.Values) {
<p>
<input type="text" name="Model.Values[#first].Key" value="#kvp.Key" />
<input type="text" name="Model.Values[#first].Value" value="#kvp.Value" />
<input type="hidden" name="Model.Values.Index" value="#first" />
</p>
}
you have to generate A Guid for the dictionary index, and you have to create 3 inputs, one for the Key, one for the Value and one for the Index of the Dictionary
Also I have submited using Jquery with the following:
$('form#frmFormId').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
//debugger;
$('#cover-spin').show(100);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false
}
);
return false;
});