Create a query suggestion page based on keywords - c#

I have an asp.net page and am writing some words in a question textbox named txtTitle. After moving to another txtbox named txtbox2, I want to open a question-suggestion page based on the keyword typed in txtbox1 in the space before txtbox2. I've tried this but it is not working. Can anyone help?
<script type="text/javascript">
$(function() {
$("#txtTitle").blur(function() { QuestionSuggestions(); });
});
function QuestionSuggestions() {
var s = $("#txtTitle").val();
if (s.length > 2) {
document.title = s + " - ABC";
$("#questionsuggestions").load("QuestionList.aspx?title=" + escape(s));
}
}
</script>

Create a WebService WebMethod in ASP.Net/C# that loads the suggestions. Your code in the WebMethod will load the datatable with the suggestions. In your WebMethod, return the DataTable as a hashtable, and it will automatically be converted to a JSON object.
public Suggestions<Hashtable> GetSuggestion()
{
DataTable dt = new DataTable();
List<Hashtable> ht = new List<Hashtable>();
string q = Context.Request.QueryString["Q"];
dt = [code to load datatable]
ht = MethodToConvertToHashTable(dt);
dt.Dispose();
return ht;
}
In your txtTitle.blur function, call question suggestions, which does a jQuery AJAX call to the webmethod (I left out the obvious).
function QuestionSuggestions() {
var s = $("#txtTitle").val();
var myJSON = $.ajax({
url: '/directory/svc/yourwebservicepage.asmx/GetSuggestion?Q=' + s,
type: 'POST',
contentType: 'application/json',
success: function (msg) {
var d = msg.d; //THIS IS YOUR JSON OBJECT
}
}
}

Related

ASP.Net Core - Store and Retrieve FormCollection in SQL Server database

I have a razor form that collects a long list of inputs from the user. I need to store the data in SQL Server. But I don't want to create that many columns in the SQL Server table. So my idea was to have a column FormData of type nvarchar(max), convert the FormCollection object to Json and store it in table.FormData.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
string json = JsonConvert.SerializeObject(collection);
MyObject form = new MyObject()
{
id = 1,
formdata = json
};
repository.Add(form);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
Storing the data works fine, but when I retrieve it, the deserialization fails.
I wrote an API to retrieve it. The return data has escape characters, and I believe that's what is causing the issue.
FormData:
[
{
"id": 1,
"formdata": "[{\"Key\":\"Name\",\"Value\":[\"Person1\"]},{\"Key\":\"EmpID\",\"Value\":[\"12345\"]},{\"Key\":\"inputDepartment\",\"Value\":[\"\"]},{\"Key\":\"inputLocation\",\"Value\":[\"\"]},{\"Key\":\"inputSupervisor\",\"Value\":[\"\"]},{\"Key\":\"inputExitDate\",\"Value\":[\"\"]},{\"Key\":\"optShouldEmailBeActive\",\"Value\":[\"on\"]},{\"Key\":\"optWhoHasAccess\",\"Value\":[\"on\"]},{\"Key\":\"__RequestVerificationToken\",\"Value\":[\"CfDJ8M9krkWO1eBMp3rh5qzs-Rv1bj07MLUgOrWTcXV-ivrIiXkHW30I0e0NYWuBtbvyjONlULoENzivw1NXfITYL1Y8CVIOoDgFW_ACPu9XLhHe8x5KUcOZ-FuLeXyR-Vj0Q7RE_lSmnDchZsB6ihVyW4bnFcKAjo9X62rknPNUHvvEjsIN7-1EHtrgMT2-TgLPkQ\"]}]",
}
]
I couldn't find a way to avoid having those escape characters when serializing.
I thought of using .replace() to remove these escape characters before storing, but I'm not sure if it's a good idea. I may end up doing that if I can't find a better solution.
============================
Deserialization Code:
Just for testing I tried deserializing right after serializing, and it fails.
Ajax Call Result of JSON.stringify(data):
Javascript Code:
Tried removing escape characters.
function getData() {
var url = baseURL + "api/itexit";
$.ajax({
url: url,
type: "GET",
success: function (data) {
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
alert(json);
var obj = JSON.parse(json);
var a = "";
$.each(obj, function (index) {
a += obj[index].Key + "\n";
});
alert(a);
},
error: function (data) {
}
});
}
After removing escape characters, alert(json):
Error in Chrome Developer Console:
This error is at JSON.parse(json);
=============================================
Update:
After fixing the javascript code, it works:
function getData() {
var url = baseURL + "api/itexit";
$.ajax({
url: url,
type: "GET",
success: function (data) {
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');
var obj = JSON.parse(json);
obj = obj[0].formdata;
$.each(obj, function (index) {
var o = obj[index];
$("#" + o.Key).val(o.Value);
});
},
error: function (data) {
}
});
}
Removed the escape characters, it fixed the issue.
These lines did the trick in the following javascript getData() method.
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');
Javascript:
function getData() {
var url = baseURL + "api/itexit";
$.ajax({
url: url,
type: "GET",
success: function (data) {
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');
var obj = JSON.parse(json);
obj = obj[0].formdata;
$.each(obj, function (index) {
var o = obj[index];
$("#" + o.Key).val(o.Value);
});
},
error: function (data) {
}
});
}

C# MVC HTML to EXCEL not working

I had a controller method to convert html to excel which worked fine when it was not a web method. But stopped working when the html string got too large. I converted it to a web method which I call via jQuery. It passes the data to the method, but no longer creates the Excel file. The code within the method has not changed. The only difference is the way I call it and the [HttpPost] decoration. The code follows:
[HttpPost]
[ValidateInput(false)]
public void ExportExcel(string aContent)
{
StringBuilder sb = new StringBuilder();
sb.Append(aContent);
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=ProjectData.xls");
Response.Write(sb);
Response.End();
}
And this is the jQuery stuff:
// namespace
var excel = excel || {};
$(document).ready(function () {
$('#ExcelUrl').on('click', function () {
var table = $('#tableName').val();
var content = $('#' + table).html();
excel.utilFunctions.exportToExcel(content);
});
});
excel.utilFunctions = (function ($) {
var exportToExcel = function (content) {
$.ajax({
url: "/Home/ExportExcel",
type: "POST",
data: { aContent: content }
}).done(function(data) {
alert(data);
}).fail(function(error) {
alert(error.responseText);
});
};
//public functions
return {
exportToExcel: exportToExcel
};
})(jQuery);
Any help is appreciated.
Found a solution. Apparently, since jQuery is doing the post, a file will never be generated no matter what you do.
I changed the jQuery function to create and submit a hidden form field that has my data in it.
$(document).ready(function () {
$('#ExcelUrl').on('click', function () {
var table = $('#tableName').val();
var content = $('#' + table).html().replace(/\s/g, "");
excel.utilFunctions.exportToExcel(content);
});
});
excel.utilFunctions = (function ($) {
// Excel export function
var exportToExcel = function (content) {
var form = $("<form></form>");
form.attr("method", "POST");
form.attr("action", "/Home/ExportExcel");
var dataField = $("<input/>");
dataField.attr("type", "hidden");
dataField.attr("name", "aContent");
dataField.attr("value", content);
form.append(dataField);
$(document.body).append(form);
form.submit();
};
//public functions
return {
exportToExcel: exportToExcel
};
})(jQuery);
Then I changed the ExportExcel controller function to return a FileStreamResult
public FileStreamResult ExportExcel(string aContent)
and modified the code that does the actual exporting
var byteArray = Encoding.ASCII.GetBytes(aContent);
var stream = new MemoryStream(byteArray);
return File(stream, "application/ms-excel", "FileName.xls");

Posting JSON object to asp.net server

i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});

download data as .xls format file

I need to download list data as .xls file.My controller code is follows.
[HttpGet]
public void AttendeeListToExport()
{
string campaign_id = string.Empty;
campaign_id = ((MemberProfile)HttpContext.Current.Profile).HOWCampaignID;
AutoCRM.Services.HOW.Attendee.Manage manage = new AutoCRM.Services.HOW.Attendee.Manage();
DataSet lst = manage.AttendeeListToExport(campaign_id);
if (lst != null)
{
if (lst.Tables[0].Rows.Count > 0)
{
DataTable dt = lst.Tables[0];
// Export all the details to Excel
string filename = campaign_id + "_" + DateTime.Now.ToString("ddMMyyyy") + ".xls";
Export objExport = new Export();
objExport.ExportDetails(dt, Export.ExportFormat.Excel, filename);
}
}
}
js code
$('#exportToExcel').on("click", function () {
alert('hi');
$.ajax({
url: "/api/Attendee/AttendeeListToExport",
async: true,
cache: false,
success: function (result) {
alert(result);
}
});
});
code executing correctly but file not downloading
You can download file through javascript in following both ways :
Using HiddenIFrame :
var downloadURL = function downloadURL(url) {
var iframe;
var hiddenIFrameID = 'hiddenDownloader';
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
Using Jquery :
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'uploads/file.doc';
});
Download now!
If your Controller action returned a FileResult, you could download this from your javascript function like this:
$('#exportToExcel').on("click", function () {
window.open("/api/Attendee/AttendeeListToExport", "_blank");
});
You can't download files using ajax. You have to use a hidden iframe or link directly to the file.

iterate through JSOn result

I have a WebMethod being called from ajax, trying to iterate through the returned data. The data being returned is "{ BusinessTypeID = 2 }". I'm trying to figure out how to just get the value 2?
//Function called from ajax
[System.Web.Services.WebMethod]
public static string[] GetTerminalBusinessTypes(string terminalID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<string> results = new List<string>();
try
{
var terminalBusinessTypes = (from bt in db.BusinessTypes
join obt in db.OxygenateBlenderBusinessTypes on bt.BusinessTypeID equals obt.BusinessTypeID
where obt.OxygenateBlenderID == Convert.ToInt32(terminalID)
select new
{
bt.BusinessTypeID
}).ToList();
for (int i = 0; i < terminalBusinessTypes.Count(); i++)
{
results.Add(terminalBusinessTypes[i].ToString());
}
}
catch (Exception ex)
{
}
return results.ToArray();
}
The ajax function:
function PopulateTerminalBusinessTypes(terminalID) {
$.ajax({
type: "POST",
url: "OxygenateBlenderCertificationApplication.aspx/GetTerminalBusinessTypes",
data: "{'terminalID':" + terminalID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var targetValue = data.d;
var items = $('#cblTerminalBusinessType input:checkbox');
$.each(targetValue, function (key, targetValue) {
alert(data[index].BusinessTypeID);
});
}
})//end ajax
}
When your web service returns the json value, asp.net wraps in an object, with the key being d and the value being your json string. Review this link for more info.
You have to parse the value string into a json object. Using jQuery (v1.4.1 or higher):
jQuery.parseJSON(targetValue);
To be honest I cannot see where your "index" is defined.
Shouldn't the alert line read
$each(targetVale, function(key, item) {
// on second look, this wont work as you are converting toString()
alert(targetValue[key].BusinessTypeId)
// this should
alert(item)
});
You could also throw a debugger; line above the alert and see the values being traversed.
You may want to try returning a JSON string from C#:
public static **string** GetTerminalBusinessTypes(string terminalID)
...
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(results);
return sJSON;

Categories

Resources