Twitter TypeAhead with Asp .Net - asp.net

Hi All can anyone provide me a good example of how to use Twitter Typeahead (http://twitter.github.io/typeahead.js/) in asp .net with database.
Thanks

In ASP.NET MVC you can create a controller action that returns JSON, like this:
view
#Html.TextBox("playerName")
<script type="text/javascript">
$(function () {
$('#playerName').typeahead({
name: 'players',
valueKey: 'playerName'
prefetch: '#Url.Action("AvaliablePlayers", "Player")',
limit: 10
});
});
</script>
controller and action
public class PlayerController : Controller
{
public JsonResult AvaliablePlayers(int groupId)
{
var group = _groupRepository.GetById(groupId);
return Json(group.Players.Select(p => new { playerId = p.PlayerID, playerName = p.Name), JsonRequestBehavior.AllowGet);
}
}
And in ASP.NET WebForms you can use custom HTTP handler to return data in JSON format, like this:
Default.aspx
<asp:TextBox id="country" CssClass="countryTypeAhead" runat="server"></asp:TextBox>
<script type="text/javascript">
$(function () {
$('.countryTypeAhead').typeahead({
name: 'countries',
prefetch: '<%= Page.ResolveClientUrl("~/Countries.ashx") %>',
limit: 10
});
});
</script>
Add new Generic Handler (.ashx) named Countries to your project. Here is the Code-behind for the handler:
public class Countries : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var cntries = new List<string>() {"Slovenia", "Italy", "Germany", "Austria"};
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
context.Response.Write(jsSerializer.Serialize(cntries));
}
public bool IsReusable
{
get
{
return false;
}
}
}
This sample uses JavaScriptSerializer which is available in ASP.NET 3.5 and above. If you are using asp.net of lover version than 3.5 you can use JSON.NET to convert typeahead results to JSON format.

Related

JSON Post Request is not working in ASP.NET5 MVC but is working in ASP.NET4.5 MVC

I have an example which sends a JSON post request to MVC controller. This example works in ASP.NET 4.5 but won’t work in the newest ASP.NET 5 release. Do I miss anything in this example?
I created a model, but I didn’t bind it to database. It will be just the object created in the memory.
public class SalesOrder
{
public int SalesOrderId { get; set; }
public string CustomerName { get; set; }
public string PONumber { get; set; }
}
I use Visual Studio 2015 to create that model based controller and its associated CRUD views. However, in this example, I will only run the “Create” view.
Inside the controller, I hard coded a SalesOrder object list and it only contains an item. I will use it to work with the CRUD views.
private List<SalesOrder> salesOrderList =
new List<SalesOrder> (
new SalesOrder[]
{
new SalesOrder()
{
SalesOrderId = 1,
CustomerName = "David",
PONumber = "123"
}
});
Inside the controller, I also create a new function to process the “Save” request. The request will just change the CustomerName property of the model then bounce back with the JSON result.
[HttpPost]
public JsonResult Save(SalesOrder salesOrderViewModel)
{
salesOrderViewModel.CustomerName = "David returns";
return Json(new { salesOrderViewModel });
}
In the Create.cshtml, I created a button and attach JQuery script to its click event.
<p><button id="saveButton">Save</button></p>
This is the JQueryScript.
$(function () {
var clickFunc = function () {
var salesOrderViewModel = {
"salesOrderViewModel": {
"SalesOrderId": 123,
"CustomerName": "ab",
"PONumber": "2",
}
}
$.ajax({
url: "/SalesOrders/Save/",
type: "POST",
cache: false,
data: JSON.stringify(salesOrderViewModel),
contentType: "application/json; charset=utf-8"
});
}
$('#saveButton').click(clickFunc)
})
I click the "Save" button in Create.cshtml to trigger the post request.
I set the debug break point in the controller and verify the coming post request. In ASP.NET 4.5, the JSON deserialization is working, and it shows all the values.
However, in ASP.NET 5, an empty object is returned.
In ASP.NET 5 case, if press F12 to start the debugger in Microsoft Edge, then it shows the Post request does have the correct values, but for some reasons, they are not passed to MVC controller.
Please see these screen shots:
http://i63.tinypic.com/68vwnb.jpg
Do I miss anything?
Thanks for helping…
I don't think you need to specify the name of the parameter. Try:
var salesOrderViewModel = {
"SalesOrderId": 123,
"CustomerName": "ab",
"PONumber": "2",
}
I think you need to especify fromBody in the Controller.
[HttpPost]
public JsonResult Save([FromBody]SalesOrder salesOrderViewModel)
{
salesOrderViewModel.CustomerName = "David returns";
return Json(new { salesOrderViewModel });
}
Thanks for DCruz22 and Stephen Muecke.
The working version of the script is:
$(function () {
var clickFunc = function () {
var salesOrderViewModel = {
"salesOrderViewModel": {
"SalesOrderId": 0,
"CustomerName": "ab",
"PONumber": "2",
"MessageToClient": "POST to server"
}
}
$.ajax({
url: "/SalesOrders/Save/",
type: "POST",
cache: false,
data: salesOrderViewModel
});
}
$('#saveButton').click(clickFunc)
})
I found the parameter name "salesOrderViewModel" is not a problem. With it, the script is still working.
Actually, this question is a simplified version of my original problem. My originally problem is starting from the knockoutJs. Below is the script doing the data binding. After user clicks the "Save" button, the self.save function() is called and the script will send the post request including the data model to the MVC controller.
SalesOrderViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/SalesOrders/Save/",
type: "POST",
cache: false,
data: ko.toJSON(self),
success: function (data) {
}
});
}
}
The problem is "ko.toJSON(self)" includes some other information. Below is the request body I captured from the Microsoft Edge debugger.
{"SalesOrderId":0,
"CustomerName":"chiang123",
"PONumber":"123",
"MessageToClient":null,
"__ko_mapping__":{
"ignore":[],
"include":["_destroy"],
"copy":[],
"mappedProperties":{
"SalesOrderId":true,
"CustomerName":true,
"PONumber":true,
"MessageToClient":true}}}
You can see all data starts from "ko_mapping" is KnockoutJs specific. Do I need to manually trim those data in order to make this work? Per information, obviously the same implementation should work in ASP.NET 4.5 but I just haven't try it yet. Many thanks...

jQuery Ajax: Parse Error Getting Result to Alert Box

I have a very simple ajax call to my handler from jquery which is failing to retrive data and it gives me parsererror when i try to show the result in alert box.
ASP.NET Handler code:
public void ProcessRequest (HttpContext context) {
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
Jquery
$('.submit').on("click",function(e) {
e.preventDefault();
var data1 = { "hi": "hello" };
alert(data1.hi);
$.ajax({
url: "/charity-challenge/CompetitionHelper.ashx",
data: data1,
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("response = " + data);
},
error: function (data, status) {
alert("FAILED:" + status);
}
});
});
Note: I can see the response coming fine in chrome while debugging. BUT somehow when i try to show it in alert box it gives me parsererror.
Also, I want to assign the json data in handler. i dont have any clue how to do that.
i have a sample calss like this in handler. how to loop through the json data and assign values to this variables so i can work on those.
public class userData
{
public string EmailAddress { get; set; }
public string EntryId { get; set; }
}
Found the work around to this.
i added a complete callback and now its showing the result in alertbox. i dont know why it is not working without it BUT if someone knows please post the answer.
here is the complete call back.
complete: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
It has to do with your request payload being sent by the ajax call as hi=hello
As a test, try this (requires Newtonsoft.Json nuget):
public void ProcessRequest(HttpContext context)
{
//string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(new { hi = "hello" }));
}
So I guess you have to parse your input stream e generate the json correctly.
You could also fix this in the client side, by calling using JSON.stringify(data1) in your data parameter in the ajax call.

Uploadify - MVC3: HTTP 302 Redirect Error (due to asp.net authentication)

I'm using uploadify to bulkupload files and I get a 302 redirect error. I'm assuming that this is because of some asp.net authentication cookie token not being passed back in the script call.
I have uploadify working in a regular bare bones mvc3 application but when I tried to integrate it within a secure asp.net mvc3 application it tries to redirect to account/signin.
I have an authentication token (#auth) that does come back as a long string within the view but I still get the 302 redirect error.
Any ideas how to send the cookie authentication data over?
View:
#{
string auth = #Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
}
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function () {
jQuery("#bulkupload").uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify.swf")',
'cancelImg': '/Content/themes/base/images/cancel.png',
'buttonText': 'Browse Files',
'script': '/Creative/Upload/',
scriptData: { token: "#auth" },
'folder': '/uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'sizeLimit': '38000',
'multi': true,
'auto': true,
'onError' : function (event,ID,fileObj,errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
});
</script>
Controller:
public class CreativeController : Controller
{
public string Upload(HttpPostedFileBase fileData, string token)
{
...
}
}
UPDATE: Ok, this works fine with IE9 but not in Chrome (Chrome throws the 302). FF doesn't even render the control.
Does anybody know how to get this working in the latest revs for
Chrome and FF?
I had similar problems when I tried to use uploadify with asp.net mvc3. After much googling this is what I found that seems to work. It basically involves declaring a custom attribute, then explicitly passing the authentication cookie into Uploadify's HTTP Post and processing the cookie manually via the custom attribute.
First declare this custom attribute:
/// <summary>
/// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
/// around a cookie/session bug in Flash.
/// </summary>
/// <remarks>
/// Details of the bug and workaround can be found on this blog:
/// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class TokenizedAuthorizeAttribute : AuthorizeAttribute
{
/// <summary>
/// The key to the authentication token that should be submitted somewhere in the request.
/// </summary>
private const string TOKEN_KEY = "authCookie";
/// <summary>
/// This changes the behavior of AuthorizeCore so that it will only authorize
/// users if a valid token is submitted with the request.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string token = httpContext.Request.Params[TOKEN_KEY];
if (token != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
if (ticket != null)
{
var identity = new FormsIdentity(ticket);
string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
var principal = new GenericPrincipal(identity, roles);
httpContext.User = principal;
}
}
return base.AuthorizeCore(httpContext);
}
}
Then declare this Action to pass the authentication cookie into your ViewData so you can pass it to the Uploadify widget. This will also be the action you invoke to instantiate the Uploadify widget later.
[Authorize]
public ActionResult UploadifyUploadPartial()
{
ViewBag.AuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName] == null
? string.Empty
: Request.Cookies[FormsAuthentication.FormsCookieName].Value;
return PartialView("UploadifyUpload");
}
This is the code for the UploadifyUpload View. It is basically a wrapper for the JavaScript which sets up Uploadify. I copied mine without changes so you will have to adapt it for your application. The important thing to note is that you are passing the authCookie into the scriptData property via the ViewData from the UploadifyUploadPartial Action.
#if (false)
{
<script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
}
#{
ViewBag.Title = "Uploadify";
}
<script src="#Url.Content("~/Scripts/plugins/uploadify/swfobject.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/plugins/uploadify/jquery.uploadify.v2.1.4.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Scripts/plugins/uploadify/uploadify.css")" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
CreateUploadifyInstance("dir-0");
});
function CreateUploadifyInstance(destDirId) {
var uploader = "#Url.Content("~/Scripts/plugins/uploadify/uploadify.swf")";
var cancelImg = "#Url.Content("~/Scripts/plugins/uploadify/cancel.png")";
var uploadScript = "#Url.Content("~/Upload/UploadifyUpload")";
var authCookie = "#ViewBag.AuthCookie";
$('#uploadifyHiddenDummy').after('<div id="uploadifyFileUpload"></div>');
$("#uploadifyFileUpload").uploadify({
'uploader': uploader,
'cancelImg': cancelImg,
'displayData': 'percentage',
'buttonText': 'Select Session...',
'script': uploadScript,
'folder': '/uploads',
'fileDesc': 'SunEye Session Files',
'fileExt': '*.son2',
'scriptData' : {'destDirId':destDirId, 'authCookie': authCookie},
'multi': false,
'auto': true,
'onCancel': function(event, ID, fileObj, data) {
//alert('The upload of ' + ID + ' has been canceled!');
},
'onError': function(event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
},
'onAllComplete': function(event, data) {
$("#treeHost").jstree("refresh");
//alert(data.filesUploaded + ' ' + data.errors);
},
'onComplete': function(event, ID, fileObj, response, data) {
alert(ID + " " + response);
}
});
}
function DestroyUploadifyInstance() {
$("#uploadifyFileUpload").unbind("uploadifySelect");
swfobject.removeSWF('uploadifyFileUploadUploader');
$('#uploadifyFileUploadQueue').remove();
$('#uploadifyFileUploadUploader').remove();
$('#uploadifyFileUpload').remove();
}
</script>
<div id="uploadifyHiddenDummy" style="visibility:hidden"></div>
<div id="uploadifyFileUpload">
</div>
For your Action that Uploadify Posts to, use the new TokenizedAuthorize attribute instead of the Authorize attribute:
[HttpPost]
[TokenizedAuthorize]
public string UploadifyUpload(HttpPostedFileBase fileData)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Form["authCookie"]);
if (ticket != null)
{
var identity = new FormsIdentity(ticket);
if (!identity.IsAuthenticated)
{
return "Not Authenticated";
}
}
// Now parse fileData...
}
Finally, to use the code we have written, invoke the UploadifyUploadPartial Action via the Html.Action Helper on any View you wish to host the Uploadify Widget:
#Html.Action("UploadifyUploadPartial", "YourUploadControllerName")
You should be good to go at this point. The code should work in FF, Chrome and IE 9. Let me know if you have problems.

Load ascx via jQuery

Is there a way to load ascx file by jQuery?
UPDATE:
thanks to #Emmett and #Yads. I'm using a handler with the following jQuery ajax code:
jQuery.ajax({
type: "POST", //GET
url: "Foo.ashx",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
jQuery('#controlload').append(response.d); // or response
},
error: function ()
{
jQuery('#controlload').append('error');
}
});
but I get an error. Is my code wrong?
Another Update :
I am using
error: function (xhr, ajaxOptions, thrownError)
{
jQuery('#controlload').append(thrownError);
}
and this is what i get :
Invalid JSON:
Test =>(this test is label inside my ascx)
and my ascx file after Error!!!
Another Update :
my ascx file is somthing like this:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server">Test</asp:Label>
but when calling ajax i get this error in asp: :(
Control 'ctl00_ddl' of type 'DropDownList' must be placed inside a form tag with runat=server.
thanks to #Yads. but his solution only work with html tag.
Building off Emmett's solution
public class FooHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write(RenderPartialToString("Foo.ascx"));
}
private string RenderPartialToString(string controlName)
{
Page page = new Page();
Control control = page.LoadControl(controlName);
page.Controls.Add(control);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Use the following jquery request
jQuery.ajax({
type: "POST", //GET
url: "Foo.ashx",
dataType: "html",
success: function (response)
{
jQuery('#controlload').append(response); // or response
},
error: function ()
{
jQuery('#controlload').append('error');
}
});
public ActionResult Foo()
{
return new ContentResult
{
Content = RenderPartialToString("Foo.ascx", null),
ContentType = "text/html"
};
}
//http://www.klopfenstein.net/lorenz.aspx/render-partial-view-to-string-asp-net-mvc-benchmark
public static string RenderPartialToString(string controlName, ViewDataDictionary viewData)
{
ViewPage vp = new ViewPage();
vp.ViewData = viewData;
Control control = vp.LoadControl(controlName);
vp.Controls.Add(control);
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
vp.RenderControl(tw);
}
}
return sb.ToString();
}
*.ascx files are rendered on the server side (inside of an *.aspx page), not the client side (where JavaScript is executed).
One option might be to create a blank *.aspx, put the user control on the *.aspx page, and then get that page via jQuery and dump the result on the page.
Edit
Based on your comment, I have another suggestion:
If you're developing a CMS style application, you should build your *.ascx controls so that they are compatible with the ASP.NET AJAX Toolkit. That will allow the users to add content to the page without doing a full refresh.
If you really want to make things nice for the user, you should check out Web Parts and ASP.NET AJAX as Web Parts were really designed so that users could customize the content on their pages.

ASP.NET MVC Controller FileContent ActionResult called via AJAX

The setup:
The controller contains a method public ActionResult SaveFile() which returns a FileContentResult.
What works:
The view contains a form, which submits to this action. The result is this dialog:
What doesn't work:
The view contains some javascript to do an AJAX call to the same controller action where the form would post. Rather than triggering the aforementioned dialog, or even the AJAX success function, the response triggers the AJAX error function, and the XMLHttpRequest.responseText contains the file response.
What I need to do:
Make the request for the file using AJAX, and end up with the same result as when submitting a form. How can I make the AJAX request provide the dialog that submitting a form shows?
Here's a quick example I made up. This is the concept LukLed was talking about with calling SaveFile but don't return file contents via ajax and instead redirect to the download.
Here's the view code:
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// hide form code here
// upload to server
$('#btnUpload').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '<%= Url.Action("SaveFile", "Home") %>',
success: function(fileId) {
window.location = '<%= Url.Action("DownloadFile", "Home") %>?fileId=' + fileId;
},
error: function() {
alert('An error occurred uploading data.');
}
});
});
});
</script>
<% using (Html.BeginForm()) { %>
<div>Field 1: <%= Html.TextBox("field1") %></div>
<div>Field 2: <%= Html.TextBox("field2") %></div>
<div>Field 3: <%= Html.TextBox("field3") %></div>
<button id="btnUpload" type="button">Upload</button>
<% } %>
Here's the controller code:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult SaveFile(string field1, string field2, string field3)
{
// save the data to the database or where ever
int savedFileId = 1;
// return the saved file id to the browser
return Json(savedFileId);
}
public FileContentResult DownloadFile(int fileId)
{
// load file content from db or file system
string fileContents = "field1,field2,field3";
// convert to byte array
// use a different encoding if needed
var encoding = new System.Text.ASCIIEncoding();
byte[] returnContent = encoding.GetBytes(fileContents);
return File(returnContent, "application/CSV", "test.csv");
}
public ActionResult About()
{
return View();
}
}

Resources