Calling a function / database update using Ajax via Jquery - asp.net

Im creating a simple "Was this useful?" form with Yes and No objects- Using ASP.net webforms.
I need the submission to be done via ajax using jquery, to prevent a user from voting multiple times on the same page.. currently i have two methods Like_Click and Dislike_click in the C# code behind the page in question.
Can anyone give me some pointers on or a link to any suitable walkthroughs for simple ajax via jquery (I'm new to ajax!)
Ive looked at using the [WebMethod] identifier on each of the methods but do not really understand this method fully.
thanks

You are probably looking for jQuery's post function. Check out the examples. You'll want to do something along the lines of:
$('.myForm').submit(function(){ //define a handler for the submit event of the form
$.post($(this).attr('action'), {useful: true}); //send data via ajax
return false; //prevents the form from submitting via a normal web request
});

You can try something like below
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var like = $('#Like').val();
var dislike = $('#Dislike').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home.aspx/UpdateDB', //UpdateDB is declared as WebMethod
async: false,
data: "{'like':'" + like + "','dislike':'" + dislike + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#Like').val('');
$('#Dislike').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
Webmethod is shown below
[WebMethod]
public static string UpdateDB(string like, string dislike)
{
//Add your stuff
}
take a look more details here Call WebMethod from jquery in ASP.NET

Related

Issue binding JSONP data with Knockout.js

I am working on a web project that involves a cross-domain call, and I decided to use Knockout.js and ASP.NET Web Api. I used the Single Page Application template in VS 2012, and implemented the Knockout class as it is. The page works great when I make JSON call from the same domain, but when I try using JSONP from the remote server the knockout does not seem to bind the data. I can see the JSON data received from the remote while making JSONP call, but knockout cannot bind the data.
Here is my JavaScript ViewModel classes:
window.storyApp.storyListViewModel = (function (ko, datacontext) {
//Data
var self = this;
self.storyLists = ko.observableArray();
self.selectedStory = ko.observable();
self.error = ko.observable();
//Operations
//Load initial state from the server, convert it to Story instances, then populate self
datacontext.getStoryLists(storyLists, error); // load update stories
self.selectStory = function (s) {
selectedStory(s); $("#showStoryItem").click(); window.scrollTo(0, 0);
storyItem = s;
}
//append id to the hash for navigating to anchor tag
self.backToStory = function () {
window.location.hash = storyItem.id;
}
self.loadStories = function () {
datacontext.getStoryLists(storyLists, error); // load update stories
}
return {
storyLists: self.storyLists,
error: self.error,
selectStory: self.selectStory
};
})(ko, storyApp.datacontext);
// Initiate the Knockout bindings
ko.applyBindings(window.storyApp.storyListViewModel);
And my DataContext class as below:
window.storyApp = window.storyApp || {};
window.storyApp.datacontext = (function (ko) {
var datacontext = {
getStoryLists: getStoryLists
};
return datacontext;
function getStoryLists(storyListsObservable, errorObservable) {
return ajaxRequest("get", storyListUrl())
.done(getSucceeded)
.fail(getFailed);
function getSucceeded(data) {
var mappedStoryLists = $.map(data, function (list) { return new createStoryList(list); });
storyListsObservable(mappedStoryLists);
}
function getFailed() {
errorObservable("Error retrieving stories lists.");
}
function createStoryList(data) {
return new datacontext.StoryList(data); // TodoList is injected by model.js
}
}
// Private
function clearErrorMessage(entity) {
entity.ErrorMessage(null);
}
function ajaxRequest(type, url, data) { // Ajax helper
var options = {
dataType: "JSONP",
contentType: "application/json",
cache: false,
type: type,
data: ko.toJSON(data)
};
return $.ajax(url, options);
}
// routes
function storyListUrl(id) {
return "http://secure.regis.edu/insite_webapi/api/story/" + (id || "");
}
})(ko);
This page: http://insite.regis.edu/insite/index.html makes the cross-domain call to secure.regis.edu, and it is not working. However the same page on secure.regis.eduinsite/index.html making JSON call works just fine.
What am I doing wrong? Any help will be greatly appreciated.
Thanks for those provided help.
I manage to solve the issue by adding WebApiContrib.Formatting.Jsonp class to my WebApi project as explained in https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp, and making a slight modification to my jQuery Ajax helper class as below:
function ajaxRequest(type, url, data, callbackWrapper) { // Ajax helper
var options = {
dataType: "jsonp",
crossDomain : true,
type: type,
jsonp: "callback",
jsonpCallback: callbackWrapper,
data: ko.toJSON(data)
};
return $.ajax(url, options);
}
Everything worked as a charm.
I suggest the following:
Create a simplified example (without Knockout) that just makes the AJAX call with simple, alert-style success and error callbacks. Affirm that it is throwing an error in the cross-domain case.
Check the following link: parsererror after jQuery.ajax request with jsonp content type. If that doesn't tell you enough, search the Web (and StackOverflow) for information on jQuery JSONP parserrors and callbacks.
If you're still stuck, and you've done #1 and seen what I expect you will see, re-write this post with your simplified example, and remove any references to Knockout (in title, tags). I know Knockout, but I don't know JSONP, and the folks who know JSONP don't seem to be touching this, so I think this question is reaching the wrong audience. Changing the title and tags to emphasize the JSONP/cross-domain aspect may get you the help you need.

How to get jQuery.Ajax to perform a normal POST with a redirect using ASP.NET MVC

I currently have a JSON object on my page which gets built up as users add items to it. This is all done in JavaScript/jQuery.
When the user is done adding items, I want to POST this object to a controller action and have the action return a strongly typed view using this data.
Currently, I have the jQuery.ajax POST sending this JSON object to an Action Method which then binds this object to my strongly typed Model. Problem is, I actually want this jQuery.ajax POST to redirect as if the JSON object were in a FORM and simply being submitted.
I also can't use the jQuery.post() method, which would redirect as required, as I need to be able to set the contentType to "application/json" so my binding works correctly. Unfortunately, the jQuery.post() method doesn't allow you to set this parameter.
I've read that the jQuery.post() method basically uses the jQuery.ajax() method, so I've been battling to get the jQuery.ajax() method to redirect.
I've also read that I can set the default contentType for all jQuery.ajax() methods which would then allow me to use the jQuery.post() method but want to try avoid this if possible.
Thanks
Edit: Updated with Saedeas suggestion:
My JavaScript on the 'Index' View:
<script language="javascript" type="text/javascript">
// Initialize the Shopping Cart object
var m_ShoppingCart = {
UserId: 10,
DeliveryInstructions: "Leave at front desk",
CartItems: []
};
$(document).ready(function () {
$.extend({
postJSON: function (url, data, callback) {
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
});
function PostDataWithRedirect() {
var url = '#Url.Action("ConfirmOrder", "Store")';
$.postJSON(url, m_ShoppingCart, function () { });
}
function AddToCart(id, itemName, price, quantity) {
// Add the item to the shopping cart object
m_ShoppingCart.CartItems.push({
"Id": id,
"ItemName": itemName,
"Price": price.toFixed(2), // Issue here if you don't specify the decimal place
"Quantity": quantity
});
// Render the shopping cart object
RenderShoppingCart();
}
function RenderShoppingCart() {
$("#CartItemList").html("");
var totalAmount = 0;
$.each(m_ShoppingCart.CartItems, function (index, cartItem) {
var itemTotal = Number(cartItem.Price) * Number(cartItem.Quantity);
totalAmount += itemTotal;
$("#CartItemList").append("<li>" + cartItem.ItemName + " - $" + itemTotal.toFixed(2) + "</li>");
});
$("#TotalAmount").html("$" + totalAmount.toFixed(2));
}
</script>
And then the Controller Action 'ConfirmOrder'
[HttpPost]
public ActionResult ConfirmOrder(ShoppingCartModel model)
{
return View(model);
}
So when the PostDataWithRedirect() JavaScript method is called it must hit the ConfirmOrder Controller Action and be redirected to the ConfirmOrder View. The Shopping Cart object on my Index view is built up entirely in JavaScript and the user then clicks a 'Proceed to Checkout' button and is redirected etc.
PS: My full working example can be found in an the article [ How to POST a JSON object in MVC ], I just need to update this code so that it can do the post and redirect as explained above
In the success method, do a location.href = "TARGET LOCATION" to cause the page to go to TARGET LOCATION.
$.ajax({
url: myurl,data,
data: myData,
// processData: false, // you may need this option depending on service setup
success: function(){
location.href = "TARGET LOCATION";
},
type: "POST",
contentType: "application/json"
});
Return a view that redirects:
controller
return View("redirectionView");
view
RedirectionView.cshtml
#{
Layout = null;
}
<script type="text/javascript">
alert("Success! Redirecting...");
window.location = "./";
</script>
EDIT
To accommodate data retention use tempdata.
controller
TempData["collectedUserData"] = collectedData;
return View("redirectionView");
RedirectionView.cshtml
#{
Layout = null;
}
<script type="text/javascript">
alert("Success! Redirecting...");
window.location = "./Rebuilder/ActionMethod";
</script>
Controller Rebuilder
public ActionResult ActionMethod()
{
if( TempData.ContainsKey("collectedUserData") )
{
var collectedData = TempData["collectedUserData"];
}
//todo: use else clause to catch data not present
use collectedData to build new view
return View();
}
Maybe I'm not following the question, but why does the classic post, redirect, get pattern not work?
[HttpGet]
public ActionResult WhateverActionName()
{
YourViewModel yvm = new YourViewModel();
//Initalize viewmodel here
Return view(yvm);
}
[HttpPost]
public ActionResult WhateverActionName(YourViewModel yvm)
{
if (ModelState.IsValid) {
RedirectToAction("OtherAction", "OtherController")
}
return View(yvm);
}
Do you mean you want to do a post, have it bind to the viewmodel for validation purposes in one controller, and then have that controller post to another controller that verifies everything? If so, I suggest taking a look at this code to post in c# http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx.
Edit: Or you could just place the data in a tempdata object if the other controller action doesn't truly require a post.
Edit 2: Wait, is the question how to do the post with jquery? If so,
$("#YourForm").submit(function () {
$.post('#Url.Action("WhateverActionName", "YourController")';
});
});
Note: may be small syntax errors, but close to that. The #Url.Action is the important part.
Edit 3: This should finally work.
jQuery.extend({
postJSON: function(url, data, callback) {
return jQuery.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
Call it in your view as
$.postJSON('#URL.Action("Action", "Controller")', yourJson, callback)
And then redirect inside the controller.

Unable to save image into my sql database

My task is to save image into the database dynamically,whenever the user browses the img and clicks save button
I am using asp.net mvc3,razor view and mysql is my database
I am trying to pass the browsed img file to the controller and there in the controller i am converting it into byte format
and save it into the db.But when i put a braekpoint it is showing null,indicating that the file is not pasing to the controller
Could anyone please help me out in this
Below is my View and Controller
$(document).ready(function () {
$("#photos").kendoUpload();
$("#save").click(function (event) {
alert("started");
url = 'Home/Details';
var b;
$.ajax({
type: "POST",
url: '/Home/Details',
data: { b: $('#photos').load(url) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (str) {
alert("hai");
alert(str.st);
}
});
});
});
Controller:
public ActionResult Details(HttpPostedFileBase b)
{
try
{
b = Request.Files[1];
byte[] imageSize = new byte[b.ContentLength];
b.InputStream.Read(imageSize, 0, (int)b.ContentLength);
Image g = new Image();
g.Img = imageSize;
dbContext.Add(g);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
}
var str = new { st = "saved" };
return Json(str, JsonRequestBehavior.AllowGet);
}
}
Firstly I don't think you can submit file using Ajax since it is against JavaScript security model. You will need to use some other way for posting it ajax way. Here are some JQuery plugin for ajax file upload :
http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/
If you want to use normal form post then you would have to set form element's encrypt property to "multipart/formdata" else the server just send file name and not the file itself.
You cannot upload files via standard AJAX
The return value of .load() is NOT the content loaded - it returns the jquery object. So you're trying to post the jquery object, NOT image data.

How do you register a callback to codebehind that is called when the service call completes?

I'm using a web service with an ASP page. I'd like to keep most of what is going on here happening on the service, but I need to call one function from the codebehind. How do I do this and keep it asynch.?
How do you register a callback to codebehind that is called when the service call completes?
Thanks!!
EDIT:
EXTRA INFO: I call an asmx web service using $.ajax from the jQuery library. I'd like to avoid too many changes, but again my end result must be calling a function from the service and upon completion calling a codebehind function, all as asynchronous as possible.
$.ajax({
type: "POST",
url: "WebService.asmx/InsertClient",
contentType: "application/json; charset=utf-8",
data: insertdata,
dataType: "json",
success: function (msg) {
pkey = msg.d;
inserted();
return false;
},
error: function (msg) {
alert(msg.status + msg);
return false;
}
});
All of that happens correctly and everything works, but I'm just having trouble trying to work in an asynchronous call to codebehind - because I need to update a dropdown to refresh its datasource - as here I have just added a new entry.
If you are calling the webservice from JS, you can hookup a OnSuccess event in JS and then do a __doPostback to your page from Javascript.
example:
`function testCall() {
WebServiceProxy.GetDocuments(param01, this.onSucceed, this.onFailure);
}
function onSucceed (result) {
// if result is ok
__doPostback(clientID, params);
}
function onFailure (result) {
}`
In the asp Page/UserControl you need to implement IPostBackEventHandler. For example that way:
public void RaisePostBackEvent( string eventArgument )
{
switch( eventArgument )
{
case "CallComplete":
OnWebServiceCompleted( new WebServiceCompletedEventArgs( value1 ) );
break;
default:
break;
}
}

JsonResult shows up a file download in browser

I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
});
return false;
});
</script>
Action method on controller:
public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
{
//create an envelope object and return
return Json(envelope);
}
If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?
You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
// IMPORTANT: return false to make sure the normal post doesn't happen!
return false;
});
return false;
});
</script>
You were almost there!
I have just started using ajax similar to this and first impressions looking at your code would indicate that you dont need to call submit on the form? You only need to do the ajax call. I may be wrong but it might be that the ajax is returning the data and the page is doing a refresh where the page data is replaced with the json data?

Resources