C# Web API Error 404 on POST - c#

I am getting an error 404 when I try and so a post on my web api and i'm not sure why i'm getting it the url and everything are correct.
http://10.0.1.96/testwebapi/api/case/UpdateCasePersonal/?id=4584&forename=Andy&surname=Wilson&email=example#example.co.uk&telephone=0166%20254%204876&mobile=0733333333&title=Mr
That is my Url to the web api code that I will put next
[HttpPost]
[Route("updatecasepersonal/")]
public string UpdateCasePersonal(string Caseid, string Title, string Forename, string Surname, string Telephone, string Email, string Mobile)
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
var query = $#"UPDATE TestDB.dbo.[crm-data] SET Title=" + Title + ", Forename=" + Forename + ", Surname=" + Surname + ", Telephone=" + Telephone + ", Email=" + Email + ", Mobile=" + Mobile + " WHERE Caseid=" + Caseid;
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
var dtb = new DataTable();
var da = new SqlDataAdapter(cmd);
da.Fill(dtb);
return "Done";
}
}
}
also I am doing it right trying to update my table like that? or have I done everything wrong as i'm not fluent in c# yet
can provide more code if needed
This is my code that calls the api
onUpdateClick(e) {
this.setState({
updatedForename: this.state.Case.Forename,
updatedSurname: this.state.Case.Surname,
updatedHomeTelephone: this.state.Case.Telephone,
updatedMobileTelephone: this.state.Case.Mobile,
updatedEmail: this.state.Case.Email,
updatedTitle: this.state.titleValue,
updatedPurpose: this.state.purposeValue,
updatedMaritalStatus: this.state.maritalValue,
updatedEmpStatus: this.state.empValue,
}, function () {
var id = this.state.Case.Caseid;
var forename = this.state.updatedForename;
var surname = this.state.updatedSurname;
var email = this.state.updatedEmail;
var homeTelephone = this.state.updatedHomeTelephone;
var mobileTelephone = this.state.updatedMobileTelephone;
var title = this.state.updatedTitle;
axios.post('http://10.0.1.96/testwebapi/api/case/UpdateCasePersonal/', {
params: {
id: id,
forename: forename,
surname: surname,
email: email,
telephone: homeTelephone,
mobile: mobileTelephone,
title: title
}
}).then(function (res) {
}).catch(function (err) {
});
});
this.setState({
hasSaved: true
});
}

If you really want to send the concatenated data in the URL, do something like this:
[HttpPut]
[Route("updatecasepersonal/{Caseid}/{Title}/{Forename}/{Surname}/{Email}/{Telephone}/{Mobile}")]
public string UpdateCasePersonal(string Caseid, string Title, string Forename, string Surname, string Telephone, string Email, string Mobile)
{
...
}
And your url should simply look like :
http://10.0.1.96/testwebapi/api/case/UpdateCasePersonal/4584/Mr/Andy/Wilson/example#example.co.uk/0166%20254%204876/0733333333/
This is not good practice.
This completely exposes your data in the request. In general, concatenation is almost never the best way to do anything related to data. You SHOULD send the data as a whole to the call instead. Something like:
[HttpPut]
[Route("updatecasepersonal/{CaseId}"]
public string UpdateCasePersonal(string Caseid, RequestDto request)
{
...
}
Of course, RequestDto should be a class you make that requires all those fields: Title, Forename, Surname, Email, etc, and pass it in your Javascript (or wherever your sending the post from). And it should be named something apt to your request. Like since this looks like user profile data, or something along those lines, something like ContactDto.

Related

ASP.NET Core 2.1 Calling Rest API in a schedule

I have this ASP.NET Core 2.1 web application. The admin gets online game codes from the page below. Selecting the game (Razer Gold Pin), quantity and email to send those codes.
A Rest API call is made for the purchase. There is a limit for purchasing, a maximum of 200 purchases can be made at one time.
At first, there wasn't much to buy so there was no problem. But the demand has increased, when there are 10 thousand, 20 thousand purchases, it is necessary to purchase from this screen for hours. I wonder can we make a large number of purchases without waiting in front of the screen with scheduling?
Here is the the Javascript in the cshtml:
$("#btn_add").html(
'<span class="spinner-border spinner-border-sm" role="status" id="spinner" aria-hidden="true"></span> Loading...'
);
var selText = $("#validationCustom04").val();
var gameName = $("#validationCustom04 option:selected").text();
var quantity = $("#quantity").val();
var email = $("#email").val();
var price = $("#total").val();
var company = $("#validationCustom05").val();
if ($("#total").val() !== '') {
price = $("#total").val();
}
var serviceUrl = '/GameBanks/A101PinAsync?quantity=' + quantity + '&game=' + selText + '&email=' + email + '&prc=' + price + '&gameName=' + gameName + '&company=' + company;
$.ajax({
type: "GET",
url: serviceUrl,
dataType: 'json',
success: function (data) {
//alert(JSON.stringify(data));
ShowResult(data);
$("#spinner").remove();
$("#btn_add").html('Add');
}, error: function (xhr, status, error) {
$("#spinner").remove();
$("#btn_add").html('Add');
var errorMessage = xhr.responseText;
alert('Error - ' + errorMessage);
}
});
Here is the controller method:
[HttpGet]
public async Task<IActionResult> A101PinAsync(int quantity, string game, string email, int prc, string gameName, string company)
{
var price = 0;
try
{
string result = null;
var dList = new DemoList();
if (prc > 0)
{
price = prc;
}
var games = new Game { Product = game, Quantity = quantity };
var content = await games.CallGameAsync("Test", "12345", game, quantity, company);
var deserializedResult = JObject.Parse(content);
var root = JsonConvert.DeserializeObject<Root>(content);
if ((string)deserializedResult["coupons"]?[0]?["Serial"] == null)
{
result = result + gameName + ":" + (string)deserializedResult["Message"] + "\n";
}
else
{
foreach (var coupon in root.coupons)
{
result = result + gameName + " Serial:" + coupon.Serial + " Pin:" + coupon.Pin + "\n";
}
}
dList.gameList = result;
// NLOG
NLogPin(logger, User.Identity.Name, DateTime.Now, result, email);
return new JsonResult(dList);
}
catch (Exception e)
{
// NLOG
NLog(logger2, "OyunPalas " + e.Message, DateTime.UtcNow,0);
return StatusCode(500,e.Message);
}
}
Here is the Web API calling method:
public class Game
{
public string Username { get; set; }
public string Password { get; set; }
public string Product { get; set; }
public int Quantity { get; set; }
public string ShopNo { get; set; }
private static readonly Logger logger2 = LogManager.GetLogger("exceptionFile");
public async Task<string> CallGameAsync(string username, string password, string product, int quantity, string company)
{
try
{
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create("http://111.111.111.111:1907//api/v2/web/purchase");
var svcCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + svcCredentials);
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("productCode", product),
new KeyValuePair<string, string>("quantity", quantity.ToString()),
new KeyValuePair<string, string>("shopNo", company),
new KeyValuePair<string, string>("safeNo", company),
new KeyValuePair<string, string>("cashierNo", company)
});
var urlEncodedString = await content.ReadAsStringAsync();
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
await streamWriter.WriteAsync(urlEncodedString);
}
var httpResponse = (HttpWebResponse) (await request.GetResponseAsync());
var response = new HttpResponseMessage
{
StatusCode = httpResponse.StatusCode,
Content = new StreamContent(httpResponse.GetResponseStream()),
};
//Read response
var htmlResponse = await response.Content.ReadAsStringAsync();
return htmlResponse;
}
catch (Exception e)
{
//NLOG
NLog(logger2, "Test" + e.Message);
throw;
}
}
public void NLog(Logger logger, string user)
{
var sb = new StringBuilder();
sb.AppendLine("Test: " + user);
logger.Info(sb.ToString());
}
}
I have to pass product (game type) to the job. I read the https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/more-about-jobs.html#jobdatamap documentation but not fully understand how to use in my case. And I wonder if I can stop/cancel the job from this page before its end time?
I really appreciate any help you can provide. I'm sorry if the question is too silly as I have no experience with this scheduling.
Edit:
I thought of a solution like this, but I'm not sure if it's viable.
The user will enter which game, how many they want to buy, and their e-mail address on the screen.
This data will be saved in a table (BulkRequest) containing this information and the status field in the SQL database. (game: ABC, quantity:20000, status:0)
One IHostedService will get the saved data in a schedule which status=0 from the BulkRequest table and the save requests with status information in a new table (GameRequests) in multiples of 100. (game: ABC, quantity:100, status:0)
Another IHostedService will get the records in 10 minutes schedule which status=0 from the GameRequests table and make the 3rd party API call. Write a response to another table (GameResponses) and set the status=1 if there is no error.
When all requests are completed (status = 1), the status in the BulkRequest table will also be updated to 1.
A third IHostedService will check the status of BulkRequest, if status=1 then maybe a fourth service will prepare a file and send the responses to the e-mail.
I do suggest reviewing message queuing tools such RabbitMQ. With this architecture you will do all the jobs using messaging protocols with no need for "scheduling" and any "x minutes schedule" s would be ommited. Also it is more stable and error handling could be done using best practice standards. More important, it is scalable and you can have multiple hostedServices even on different servers process items in queue:
When request is registered send a message (publish) to the queue.
The hostedService1 receives the item and process it (consume). Multiple services may subscribe to process requests.
The hostedService1 may do all the job it self or even dispatch some parts to other services using the same method
The solution you proposed is doing the same job with an ad-hoc process. In fact you are reinventing the wheel. Hope it helps.

How to access a specific Post parameter in an HTTP Post WebHook?

I'm using JotForms to send a POST Message using the WebHook integration. This is the message that is sent.
RequestBin Message
I'm implementing a WebService in C# using Azure Functions in order to Insert the values from the form to an SQL-Server.
#r "System.Data"
using System.Net;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string name = "";
dynamic body = await req.Content.ReadAsStringAsync();
log.Info(body);
var e = JsonConvert.DeserializeObject<Person>(body as string);
name = e.firstname + " " + e.lastname;
//Connect to SQL
var cnnString = "Server=tcp:XXXX.database.windows.net,1433;"+"Initial Catalog=XXXX;"
+"Persist Security Info=False;"+"User ID=XXX;"+"Password=XXXX;"+"MultipleActiveResultSets=False;"
+"Encrypt=True;"+"TrustServerCertificate=False;"+"Connection Timeout=30;";
using (SqlConnection conn = new SqlConnection(cnnString))
{
conn.Open();
// Insert Signup
var signupInsert = "INSERT INTO [dbo].[test_data] ([firstname],[lastname],[date])" +
"VALUES ('" + e.q8_FirstName + "','" + e.q9_yTus + "','" + e.q24_Birthday + "')";
// Execute and load data into database.
using (SqlCommand cmd = new SqlCommand(signupInsert, conn))
{
var rows = cmd.ExecuteNonQuery();
}
return name == " "
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Ok" );
}
}
public class Person{
public string firstname {get;set;}
public string lastname {get;set;}
public string date {get;set;}
public string q8_FirstName {get;set;}
public string q9_yTus {get;set;}
public string q24_Birthday {get;set;}
}
I've managed to insert sucessfully when I test with a body that is just the JSON
{
"firstname": "ni\u00f1o",
"lastname": "Lachner2",
"date":"08/08/1994",
"name":"Vincenz2",
"slug":"submit\/80565829893878\/",
"input_language":"Espa\u00f1ol",
"q8_FirstName":"Nombre",
"q9_yTus":"Apellido",
"q24_Birthday":"08\/08\/1994",
"q5_cedula":"115850853",
"q18_country":"Costa Rica",
"dropdown_search":"",
"q3_province":"San Jos\u00e9",
"q11_cantonSanJose":"Alajuelita",
"q12_cantonAlajuela":"",
"q13_cantonHeredia":"",
"q14_cantonCartago":"",
"q15_cantonPuntarenas":"",
"q16_cantonPuntarenas":"",
"q17_cantonGuanacaste":"",
"q6_phone":"88141833",
"q2_mail":"vincenz.lachner#gmail.com",
"q7_shirtSize":"S",
"q25_channel":{"0":"Correo electr\u00f3nico","other":"YOU"},
"q27_politicaDe":"Accepted",
"preview":"true"
}
How can i access the JSON in the rawRequest? That is in the RawBody under the name rawRequest.
and what are these separators? --------------------------e5d83c25c3d6dcc0
--------------------------e5d83c25c3d6dcc0
Content-Disposition: form-data; name="rawRequest"
{"slug":"submit\/80565829893878\/","input_language":"Espa\u00f1ol","q8_FirstName":"textbox_sample0","q9_yTus":"textbox_sample1","q24_Birthday":"11\/11\/1111","q5_cedula":"1","q18_country":"Costa Rica","dropdown_search":"","q3_province":"San Jos\u00e9","q11_cantonSanJose":"Alajuelita","q12_cantonAlajuela":"","q13_cantonHeredia":"","q14_cantonCartago":"","q15_cantonPuntarenas":"","q16_cantonPuntarenas":"","q17_cantonGuanacaste":"","q6_phone":"1","q2_mail":"john#example.com","q7_shirtSize":"XS","q25_channel":["Facebook"],"q27_politicaDe":"Accepted","preview":"true"}
It should be something like
var form = await req.Content.ReadAsFormDataAsync();
var body = form["rawRequest"];
If you send the message from JotForms, You could use the following code to get the
rawRequest or you could get pretty property value that is the fields in the JotForms.
The following is my detail steps:
1.Create the JotForms
2.Add the follow code to get the rawRequest
if (req.Content.IsMimeMultipartContent())
{
var content = await req.Content.ReadAsMultipartAsync();
var test = content.Contents.ToList();
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in test)
{
var value = await item.ReadAsStringAsync();
dic.Add(item.Headers.ContentDisposition.Name, value);
log.Info(value);
}
foreach (var item in dic)
{
log.Info($"{item.Key}:{item.Value}");
}
}
3. Remote debug on my side.

using try catch block in webservice and sending the result in angularjs controller

i am creating a web app in which i am updating the records with web service and then sending the email to the particular person from another method in web service
for ex
i have two methods
1 for update
2 for sending mail
public void updcomson(string Id, string upddate, string updcomname, string updbrandname, string updzone, string updlocation, string updstartime, string updendtime, string updprogram, string updvenue, string updvenuename, string pm, string pax)
{
//updating
SendEmailsms();
con.Close();
var json = js.Serialize(message);
Context.Response.Write("{" + '"' + "message" + '"' + ":" + json + "}");
}
SendEmailsms();
this line is calling the second method
in my second method i am calling a stored procedure which looks like this
// automail store procedure email send dynamically
SqlCommand cmd = new SqlCommand("sonvinmailsmssend", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#brandname", brandname.ToString());
cmd.Parameters.AddWithValue("#zone", zone.ToString());
cmd.Parameters.AddWithValue("#location", location.ToString());
cmd.Parameters.AddWithValue("#property", property.ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
but sometimes there are multiple records save with the same name in my database so i get the error
subquery returns more then 1 value
i just want to use try catch block here
like
try
{
// automail store procedure email send dynamically
SqlCommand cmd = new SqlCommand("sonvinmailsmssend", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#brandname", brandname.ToString());
cmd.Parameters.AddWithValue("#zone", zone.ToString());
cmd.Parameters.AddWithValue("#location", location.ToString());
cmd.Parameters.AddWithValue("#property", property.ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch
{
//what i need to write here??
}
what i need to do in my controller??
$http.get('/csuv5.asmx/updcomson', {
params: {
//params
}
})
.then(function (response) {
//what i need to do here?
});
service:
you need to change return type of your updcomson to list or Dictionary
public List<string> updcomson(string Id, string upddate, string updcomname, string updbrandname, string updzone, string updlocation, string updstartime, string updendtime, string updprogram, string updvenue, string updvenuename, string pm, string pax)
{
//updating
string errMessage = SendEmailsms();
con.Close();
var json = js.Serialize(message);
Context.Response.Write("{" + '"' + "message" + '"' + ":" + json + "}");
List<string> plist = new List<string>();
plist.Add(errMessage);
return plist;
}
//Exception block of SendEmailSMS(), change return type to string from void
catch(Exception ex){
// return the message you want to
return ex.Message;
}
Angular: something like this
$http.get('/csuv5.asmx/updcomson', {
params: {
//params
}
})
.then(function (response) {
$scope.returnMessage= response.data;
//now you have your returned value in $scope.returnMessage, use it in alert or to show in a label as error
});
//////
small example from my code
/////
public class LoginController : ApiController
{
[HttpPost]
[Route("api/Login/Authenticate")]
public bool isAuthenticate(LoginVal val)
{
bool auth = false;
using (HostingEnvironment.Impersonate())
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
if (ctx.ValidateCredentials (val.UserID, val.Password))
{
auth = true;
}
}
return auth;
}
}
Angular:
var LoginApp = angular.module('LoginApp',[]);
LoginApp.controller('LoginController', function ($scope, $http, $window) {
$scope.LoginAuth = function ()
{
var dataToPost = {
'UserID': $("#txtUserid").val(),
'Password': $("#txtPassword").val()
}
var url = 'http://localhost:52212/api/Login/Authenticate';
$http.post(url, dataToPost).then(function (response) {
$scope.isAuth = response.data;
if ($scope.isAuth) {
//$window.location.href = 'Index.html';
$window.location.href = 'customscripts/js/Index.html';
}
else
{
alert("Wrong Username/Password");
//$window.location.href = 'Login.html';
$window.location.href = 'customscripts/js/Login.html';
}
});
}
});
You can return an IHttpActionResult from your controller:
//C# controller
//You also need to inherit your controller from ApiConroller
// public class MyController : ApiConroller {//the code...}
public void updcomson(string Id, string upddate, string updcomname, string updbrandname, string updzone, string updlocation, string updstartime, string updendtime, string updprogram, string updvenue, string updvenuename, string pm, string pax)
{
try{
//do work...
return OK(myResult);
}
catch(){
return NotFound();
}
}
Angular service:
$http.get('/csuv5.asmx/updcomson', {
params: {
//params
}
})
.then(function (response) {
// do something with the response
},function(error){
// handle error
})

MVC - Redirect to view after "$.post" to controller

On the click of a button:
$("#newSave").click(function () {
AddNewAccount();
});
I am making a function call to:
function AddNewAccount() {
$.post("/RxCard/AddAccount",
{
NewAccountName: $("#newAccountName").val(),
NewAccountAddress: $("#newAccountAddress").val(),
NewAccountCity: $("#newAccountCity").val(),
NewAccountState: $("#newAccountState").val(),
NewAccountZip: $("#newAccountZip").val(),
NewAccountArea: $("#newArea").val(),
NewAccountPrefix: $("#newPrefix").val(),
NewAccountSuffix:$("#newSuffix").val()
}, function (errorMsg) {
if (errorMsg.length > 0) {
$('div#divSearchList').empty();
$('div#divSearchList').html(errorMsg);
}
else {
loadAccount(accountId, false);
}
});
$("body").css("cursor", "default").delay(1000);
}
from there the data is passed into the controller action:
public ActionResult AddAccount(string NewAccountName, string NewAccountAddress, string NewAccountCity, string NewAccountState, string NewAccountZip, string NewAccountArea, string NewAccountPrefix, string NewAccountSuffix)
{
DuplicatesPage model = GetDups(NewAccountName, NewAccountAddress, NewAccountCity, NewAccountState, NewAccountZip, NewAccountArea, NewAccountPrefix, NewAccountSuffix);
return RedirectToAction("DuplicatePage", model);
}
in order to generate the model (for the view i am attempting to display) from:
private DuplicatesPage GetDups(string NewAccountName, string NewAccountAddress, string NewAccountCity, string NewAccountState, string NewAccountZip, string NewAccountArea, string NewAccountPrefix, string NewAccountSuffix)
{
DuplicatesPage model = new DuplicatesPage();
duplicates results = new duplicates();
var phone = NewAccountPrefix.ToString() + NewAccountSuffix.ToString();
var datenow = DateTime.Now;
var firstofmonth = new DateTime(datenow.Year, datenow.Month, 1);
OdbcCommand cmd1 = new OdbcCommand();
cmd1.CommandText = "{call dbo.Maint_AddClinic(?,?,?,?,?,?,?,?,?)}";
cmd1.Parameters.AddWithValue("#Name", NewAccountName);
cmd1.Parameters.AddWithValue("#Address", NewAccountAddress);
cmd1.Parameters.AddWithValue("#City", NewAccountCity);
cmd1.Parameters.AddWithValue("#State", NewAccountState);
cmd1.Parameters.AddWithValue("#Zip", NewAccountZip);
cmd1.Parameters.AddWithValue("#AreaCode", NewAccountArea);
cmd1.Parameters.AddWithValue("#PhoneNumber", phone);
cmd1.Parameters.AddWithValue("#StartDate", firstofmonth);
cmd1.Parameters.AddWithValue("#AccountTypeID", 2);
cmd1.Parameters.AddWithValue("#IgnoreDupAddress", 1);
DataTable dt = GetData(cmd1);
foreach (DataRow row in dt.Rows)
{
Pharmacy pharmacy = new Pharmacy();
pharmacy.AccountName = row["AccountName"].ToString();
pharmacy.Address = row["Address"].ToString();
pharmacy.City = row["City"].ToString();
pharmacy.ZipCode = row["ZipCode"].ToString();
results.Pharmacies.Add(pharmacy);
}
results.Count = dt.Rows.Count;
model.DupResults = results;
return model;
}
and end at:
public ActionResult DuplicatePage()
{
return View("Duplicates");
}
The problem is that I am not redirected to the view Duplicates. I just stay on the same page. The problem is probably obvious but I cant seem to locate it. I tried redirecting after making the call to AddNewAccount on the button click but my model for Duplicates is not generated at that time.
The problem is that you are using RedirectToAction with an AJAX call and that will never work because the RedirectToAction will return a redirect response HTTP 302 to your AJAX call, and your AJAX call will not consume this response as you expect, and no redirects will ever happen.
To fix this you need to change your $.post to a full post back, or send the url to redirect to with a response and do the redirect manually on the client side and then for example use: window.location.href = 'new-url-to-go-to';

Ajax Request to Web Method Returning document object instead of text or JSON

I have an ajax call to a web service which I'd like to return some JSON back to the view. Right now, though, if I alert the result of the call, I get "object Document". I tried changing the content type around but no dice. Here is the ajax call in its current state:
$.ajax({
type: "GET",
url: "services/offerService.asmx/getUploadedDocs",
contentType: 'text/html',
data: {offerID : offerId},
success: function(result) {
$.each(result, function(index) {
alert(result.toString());
$(element).closest('ul.uploadedDocs').append('<li id="uploadedDoc-'+(index+"") + '" class = "uploadedDocument"><span id="uploadedDocTitle">Title: '+ result["title"] + '</span><span id="uploadedDocUploadedBy>Uploaded By: ' + result["uploadedBy"] + '</span></li>');
});
}
});
And here's the web method:
[WebMethod]
public object getUploadedDocs(string offerID)
{
string sql = "SELECT * FROM [dbo].[uploaded_documents] WHERE primary_offer_id = #offerId";
IList<UploadedDocument> uploadedDocs = new List<UploadedDocument>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["production"].ToString()))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#offerId", SqlDbType.Int);
cmd.Parameters["#offerId"].Value = offerID;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
adapter.Dispose();
uploadedDocs = dt.ToList<UploadedDocument>();
}
StringBuilder json = new StringBuilder();
json.Append("{");
int count = 1;
foreach (UploadedDocument doc in uploadedDocs)
{
json.Append("{doc"+count.ToString()+":"+"{\"title\": " + doc.docTitle + ", \"uploadedBy\": " + doc.uploadedBy + ", \"uploadDate\": " + doc.uploadDate.ToLongDateString() + "},");
}
if(json.ToString().Contains(","))
json = json.Remove(json.ToString().LastIndexOf(','), 1);
json.Append("}");
return json.ToString();
}
I could send it back as a object(), probably, but I'd much rather leave it as a string and have it be parsed as JSON. Any ideas?
First, you need to change the contentType in your ajax call to 'json'.
Then try calling
alert(JSON.stringify(result));
and see what that gives you. Assuming you are constructing the json object properly, it should be working. Also download firebug and see what is being returned.
Edit:
I'm not sure what your uploadedDocs object looks like but try doing
return Json(uploadedDocs);
in your method.
JK you're using WebForms (?) so to parse it to a Json object see here

Categories

Resources