Update SQL Database from client side in ASP.NET - c#

I am kinda new in web development, looking for secured way to update SQL Database from the client side, or in other description updating the database without refreshing the webpage like (like facebook button).
I searched a lot and found that it can be done by using a web service and call it by javascript or using javascript direct or ajax, but which is the best and secured way and there is any other way to do it ?
thanks..

you can use ajax for updating database from client side.. Like if you click a button in web page, get the click event of that page through JavaScript or jQuery then through ajax you can perform database update. See the code below:
For catching event(like my button id is button1):
$('#<%=button1.ClientID%>').click(function{
$.ajax({
type: "POST",
url: "default.aspx/UpdateDatabase",
data: "{'textboxvalue':'" + $('<%=textbox1.ClientID%>').val() + "'}'
contentType: "application/json;charset=utf-8",
datatype: "json",
success: UpdateDone
});
});
In above code you have passed one value from a textbox1 to function UpdateDatabse in Default.aspx page(Please defined this function as [WebMethod]). then do your update in this function and return some string or bool value so that you can judge that update is done then value in success is name of function that will run if your function runs successfully so define that function in JavaScript or jQuery like
function UpdateDone(response)
{
if(response.d == 'done')
{ alert('Update is done'); }
else
{ alert('Sorry Update not done'); }
}
Above code will not do any postback you see that your value is updated in database. Please note that the function you make in C# page please mark it as WebMethod and it will be a static method, then only your JavaScript can find that function.
Hope this will resolve your problem.

The term ajax you use is correct but already a bit old. The new kids on the block are called SPA's where SPA stands for Single Page Application
It does what you want to achieve to the extreme: no more page refreshes. So it seems a good way to start
Here is The ASP.NET Single Page Application homepage
My advice is to research and invest time in one of the (many) javascript frameworks that will help you achieve this goal much faster. Hand coding javascript and make it work cross browser is too much work. The ASP.NET team choose upshot.js to solve your problem and it seems a fine choice.
Screenshot take from here

I found doing AJAX with JSON with ASP.NET MVC 3 to be easiest method of doing AJAX requests. Then you can have a specific action method that handles the request and makes the updates the database via Entity Framework(EF).
Essentially only passing the data that needs to be updated in the JSON. From there the MVC Action receives the JSON, and uses EF to lookup the DB record, apply/save changes. It can even respond with a success message which your AJAX can use to update some field that verifies the data was saved for the user(you could even do something where you have a "Saving..." message appear between the first ajax request and the response.)
This will allow you to send the request without refreshing your page. All your DB access code will be server side in the Action method.
This example shows how you might do a json request. You would modify this by adding additional code to the Create method to interact with entity framework(or your database tool of choice) to update a record based on the Person person parameter that was passed in(notice MVC did a really nice thing of converting the json data into a nice Person class!)
http://juristr.com/blog/2011/08/posting-json-data-to-aspnet-mvc-3-web/
If the data the user will enter in the webform is sensitive, you would need to encrypt it before sending the json request. I would personally just setup the website to use SSL. Anything you cook up on your own probably won't be as secure as SSL.
The code you add to the Create method might look like this:
//Find the person that they are attempting to edit
Person currentPerson = db.Persons.Find(person.PersonKey);
//update the database fields based on the submitted data(I would probably actually use AutoMapper for this
currentPerson.Name = person.Name;
currentPerson.DateOfBith = person.DateOfBirth;
//etc.
db.SaveChanges();
//compose a JSON response object indicating success, you would want to combine this with a try catch in the above to reply regarding failures as well

Related

ajax submit to WebAPI controller

I'm not sure of the best way to accomplish my goal. Looking for insight. I'm familiar with WebAPI services consumed through WPF and Silverlight but this is my first run at ASP and MVC.
I am building a site to verify contents of a shipment against an electronic manifest (EDI 856). I have a page that displays the shipping data and I need the users to scan each item barcode in the container. I would then like to pass that barcode to a service, verify the item belongs in that shipment and then update the page to show as much.
My plan was to have a single text box into which the user could scan/type the barcode and then submit that data to a WebAPI service which would verify the information and then probably use SignalR to send a message back to the page and update a grid with the item data.
If this is a decent way to go, I'm just not quite sure how to use ajax to call the WebAPI endpoint and provide the data I need.
I would advise against using SignalR in this situtation. What you need, judging from your description, is the most basic use case of submitting an ajax request and receiving a response.
You are not designing a system where you need the server to initiate communication with the browser or anything like that, where sockets (and SignalR as an abstraction over sockets with fallbacks to less suitable protocols) is a huge overkill.
Don't worry, your use case is rather simple.
It's a little out of scope to describe how to setup a WebApi project, how to configure routing, action names, etc. Simple google searches will surely provide ample quality tutorials on getting started.
I'll just try to explain what the general idea is, with some code samples, to get you thinking in the right direction.
You need to create an ApiController.
The simplest version of that Controller will probably look something like this:
public class ShipmentVerificationController : ApiController
{
//this is the response object you will be sending back to the client website
public class VerificationResult
{
public bool Valid;
}
public VerificationResult GetIsItemValid(string BarCode)
{
bool itemIsValid;
// Implement checks against the BarCode string here
itemIsValid = true;
return new VerificationResult { Valid = itemIsValid };
}
}
Note that the inner class represents the response you will be sending back. It should be properly filled out with additional info if needed and probably put into a separate .cs file in the "Models" folder or where ever you see fit.
I have declared it inside the controller for demonstration purposes only
Once you have a WebApi service deployed, it's really easy to send it data from your website and receive the feedback.
To simplify Ajax requests, jQuery is often used.
Once the user inputs the barcode into a textbox, you can hook up an event to check for return key being pressed (most barcode scanners send the return key command after they input the barcode data) and then write something along the lines of:
var barcode = $("#input-field").val();
$.getJSON( "<url_to_your_webapi_service>/api/ShipmentVerification/GetIsItemValid/" + barcode, function( data ) {
if (data.Valid) {
// great, highlight the item as valid
}
else {
//better indicate an error with the scanned item
}
});
Please note that for simplicity I have not included any error handling, url parameter encoding, and most importantly, zero authorization.
Authorization is very important if you deploy the web service to the open web but still do not want anyone to be able to call it.
You will have to research these topics yourself, but I hope I have presented you the core concepts and logic behind a simple service such as this, so you have a base to start with.
If you come up with specific problems and questions post a new question.
I actually found a more simple way to do this. I nixed the idea of using a WebAPI endpoint and just went with a normal controller. I used ajax to prevent the page from refreshing with the new view, since that view is actually just json data with my return values in it.

passing javascript parameters and using them in unity C# files

I want to pass some javascript parameters at runtime (webplayer) to unity and using them in my network.cs script.
<html>
<script type="text/JavaScript">
//<![CDATA[
PlayerName = "Adam";
playerID = "56";
//]]>
</script>
</html>
Just consider I am using the above parameters to log in users.
You need to send the data from the webpage to the Unity3d container. You can do something like this:
u.getUnity().SendMessage(GameObjectName,MethodName,stringParam);
where:
u is the Unity3d container object created by unity if you use their template.
GameObjectName is the name of a game object that you placed somewhere on the stage
MethodName is the name of a method that's available for that GameObject, that means that it will be a method defined in one of the components (MonoBehaviour) that you attached the the GameObject
stringParam si the parameter that you pass to MethodName, the method can only accept one string param, so you need to serialize your data, you can use JSON.parse( {"playerName":PlayerName,"playerId":playerID} )
On the C#/Unity side you need to implement a MonoBheviour that has a
void MethodName(string param);
defined that reads the string and with a JSON parser gets the data out.
You would need to post that data back to your server. Using AJAX is probably want you want if you don't want your whole page to reload.
A commonly used framework, facilitating ajax is jQuery.
You would need an endpoint, writting in your c# (guessing from your fileending on network.cs) to read what your clientside javascript is posting. I don't know what version of .net you are on, but look into WebAPI - it is very easy to implement.
TL;DR
Use javascript/jquery to post your data from the client to the server.
Read the posted data on your serverside, though either WebAPI or just a normal .aspx page reading querystring/form values
If you just want to send data from the client, and not worry about any response, you can use
$.ajax({
type: "POST",
url: url,
data: {PlayerName: PlayerName, PlayerId: playerID},
});
You can change POST to GET if you want the make a get request instead. The data will be readable through Request.Form or Request.QueryString if you use a normal .aspx page for url. If you use WebAPI, it will be injected into your methods parameters.

read Json data from a webservice using jQuery or C#

I have the following API which returns json data as follows:
API : http://data.mtgox.com/api/1/BTCUSD/ticker
JSON : {"result":"success","return":{"high":.......
using jquery i tried the following but it is not giving me the data.
$.getJSON('http://data.mtgox.com/api/1/BTCUSD/ticker', function (data) {
alert(data);
});
and
$.ajax({
type: 'GET',
url: 'http://data.mtgox.com/api/1/BTCUSD/ticker',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error + "error");
}
});
but in first i get no alert
and in second i get error alert.
How can I read this data using jQUERY or C#?
THanks
As Archer mentioned this won't work if you're not on the same domain. There is one way around this using CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) but you'd need to have control over the domain to set the required header or at least get the person in charge to do so.
The other option is to use JSONP which basically wraps the result in a function call that runs immediately when it returns by injecting a script tag. Problem is you lose nice things like error handling and you can't cancel the request.
I tried your problem. The error showed in Google Chrome Javascript Console was Origin http://localhost:1564 is not allowed by Access-Control-Allow-Origin
Check the answer to this Question and find your way out.
Is live data required ? Like "I must see the data as current as from this exact second" ?
If not (probably that is the case), I suggest you make a scheduled process (let's say every 5 min) on the web server. That will get data from the source (http://data.mtgox.com) and put it into database table.
After that you make your own JSON service (an MVC action method) and publish the data from your tables.
It will also allow your customers that your site is working even if mtgox.com is down for some reason.
How to getting Data through web Services with jquery in asp.net c#.
for more details
http://way2finder.blogspot.in/2013/08/how-to-getting-data-through-web.html

Using Server side method from Javascript without AJAX

I have a tricky problem. I am in a situation where I need to use a method defined in a .cs file from a javascript function. The problem is we are using .NET 1.1 and AJAX cannot be used for the application.
Also, I will need to pass a string from the javascript to the server side method. The page where I am implementing the javascript is a .as Any ideas?
I have tried doing a post back and creating a RaisePostBack event handler method (both in the .aspx page and the .ascx user control) but no luck.
It will be greatly appreciated if someone could help me out with the problem.
To be more precise. I have a class Attachment.cs which has a method Delete().
The javascript is called from a span's onclick event. The javascript function's input parameter would be a string which I will need to use to instantiate an Attachment.
I created a method which instantiates an Attachment using a string and calls the corresponding Delete() method for the Attachment object.
Now, I will need to pass the string from javascript function to the method I have created. I cannot use PageMethods.
The Javascript function is like:
// File ID is a string
function DeleteAtt(fileID)
{
//I tried PageMethods here, tried posting the page and getting the value through
// a RaisePostBack event etc. No luck.
}
The cs method I created is like:
public void DeleteAttachment(string ID)
{
Attachment obj = new Attachment(ID);
obj.Delete();
}
Do you mean that Microsoft's "ASP AJAX" is not an option, or do you mean that any jquery/any other library, or your own hand written javascript ajax won't work? ASP AJAX may not be supported by you version of .net, but surely simple javascript will still work, as you want to access the page from javascript.
If this is the case, something as simple as this, using jquery, would work:
function submit() {
$.post(
"pagename.aspx?string=" + variable,
function (data) {
alert("Response: " + data);
});
}
How about adding a callback-url as a query string to the url that you need to submit data to? Example:
Initial Page:(javascript)
function send(){
window.location = "submiturl.aspx?str=var&
callbackurl=http://www.myurl.com/page.aspx";
}
submiturl.aspx then catches both query strings [str] and [callbackurl], performs the action/function and then sends a response back to the [callbackurl]
response.redirect(callbackurl + "?response=" + data);
Initial Page now uses response.querystring to determine if it was succesful/whatever else you want and continues its business.
This definitely does not use ajax, and would be, by no means, asynchronous, but is based on a pretty lengthy history of API/callback & response design.
You can inject an invisible Iframe into the page and the SRC of the iframe can be used to pass data back to the server.
This is a very old technique back before jQuery and Prototype were invented.
See: http://www.ashleyit.com/rs/ for other alternatives.

MVC: How to refresh a view

In my controller class I return some data to my view and it's all good.
Can i do something like this?
public ActionResult List()
{
while (true)
{
Thread.Sleep(3000);
return View("ListStatus", data);
}
}
Of course the above code won't work as when the return statement is ran the function exists.
I'm sure i can use some Ajax in the View itself to pull data up from the server every 3 second but for my current purpose it would just be easier to do what i'm attempting in the above code
It seems you're trying to do the refresh from the server side. Like 'pushing' the updates to the client. That's not how asp.net works. The client makes a request and the server then sends a response. This alone means you cant do the above.
Like jcm said, you need to have the client/browser making the follow-up requests for updated data.
I'd suggest a js/ajax/jQuery option. You can google and get heaps of examples.
Use meta tag <meta http-equiv="refresh" in your header, if you want to refresh the whole page.
Use jquery solution, if you want to refresh parts of the page.
Auto-refreshing div with jQuery - setTimeout or another method?
http://dev.kafol.net/2008/10/jquery-update-divs-html-dynamically.html
http://docs.jquery.com/Ajax

Categories

Resources