Ajax to WCF Service - c#

I am having a WCF Service (Ajax-enabled) and I need to call its methods using AJAX. The WCF Service name is NameService.svc and it is located within a WebService folder at the root directory of the Website. Here is how things work: I have to create a user control which includes a table layout containing the text fields to collect the user data and when clicking the button I need to use jQuery and Ajax to call the methods which will insert the data to the database. I tried the following code but it did not work for me and I need to know what I am missing or wrote incorrectly within the user control:
$(function() {
$('button').click(function() {
var name = $('text').val();
$.ajax({
url : 'NameService.svc/InsertData',
data : { suppliername : name },
method : 'post',
datatype : 'json',
success : function(data) {
alert(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr>
<td>Supplier Name:</td>
<td><input type="text" name="sname"></td>
</tr>
<td colspan="2"><button type="button" class="btn btn primary">Insert</button></td>
</tbody>
</table>
Note I am using Bootstrap within my project. Is there a problem using the button element instead of input element with type as submit? What have I missed in the url of the ajax call? Should the method within the WCF Service be decorated with specific attributes? If I will call a method that will return only data should I use the data property within the Ajax call or ignore it also the method will be post to or it should be get in that way.

If you are doing $.ajax for http post and get. I will recommend you watch the tutorial from https://www.udemy.com/rest-wcf-service-in-aspnet/learn/v4/t/lecture/5225772
After you retrieve the data, you can do a database connection from svc.cs and import these data(s) to your database. I assume you have already know how to do database connection. If no, just do some online search, you probably will learn that.
However, I have no clues if your data is in nested json format. I am struck at there also... sighh

Related

call/answer between PHP and ASP.NET

Is it possible to submit an email address through a text area of an HTMLpage integrated in ASP.net page and send this to a PHP script that control if is actually a valid email address and send answer back to the ASP page so I can get an alert: VALID or NOT VALID.
I have 2 webspeace with two different websites: ASP.net and one in PHP.
The ASP.net page has a Webform in HTML. I would like to use this to send the email to the PHP script. which rune the validation and send back the status to the ASP page that would answer through an alert, "mail valid" or "not valid."
The idea I have is that the script (after the validation control) has to send back an answer throw an URL to the ASP page and the ASP page would "listen"/ "get" this URL as a variable in order to diplay with an alert the result of the PHP SCRIPT
PHP side:
<form action="http://www.exemple.com/scripts/mailvalidation.php" method="post" id="webform">
SCRIPT PHP ? (maybe using the PHP FILTER_VALIDATE_EMAIL) ?
ASP.NET ?
Any suggestion=?
Sounds like a perfect place to use AJAX. It is independent of the language you use. PHP, ASP.NET, JSP it is all the same. All that is needed is simple JavaScript or Jquery.
In your ASP Page,
<form id="myform">
<input type="email" id="email" name="email" />
<button>Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="application/javascript">
$(document).ready(function(){
var formvars = $("#myform").serialize();
var url = "http://www.example.com/your_page.php?" + formvars;
$.ajax({
url: url,
cache:'false',
dataType: 'text',
type:"GET",
success: function(data){
//alert( data );
alert( data );
if(data =="1")
alert("VALID");
else
alert("IN VALID");
},
error: function(data){
alert('error; '+ eval(error));
}
});
});
</script>
In your php script,
<?php
$email = $_REQUEST["email"]
if($email, FILTER_VALIDATE_EMAIL))
echo "1";
else
echo "0";
?>
Good luck.
I would say if the issue is of passing value from asp to php, then use querystring to pass value from one page to another.
But as far as your comment goes...you can directly use ASP to insert the records in MYSQL without passing through PHP.
YOu can use the following as the reference:
http://www.codeproject.com/Articles/36484/Working-C-code-for-MySql-Stored-Procedures-IN-OUT
in php file use:
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$msg='valid';
}
else{ $msg='invalid'; }
$urlVar='email='.$_POST['email'].'&msg='.$msg;
header("location: hostname/PageName.asp?$urlVar");
then in asp you can use above code and execute your msg in if condition as shown:
if(Request.QueryString("msg") != ' ' && Request.QueryString("email") != ''){
}
I am not good in asp but hope you get concept to handle it
I would suggest, validate email in asp.net. There is lot you can do to validate email in asp.net. Like use Regular Expression - refer this, or use EmailValidator to validate. Also check this link - Email Address Validation for ASP.NET
Following is an example of the above.
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
But if you are interested to know how to communicate between asp.net and php, then you can check following.
Have php page that accepts email as get request, php page can use FILTER_VALIDATE_EMAIL to validate email or any other custom validation you want to add.
Then use jQuery ajax in asp.net webform to invoke that page with get request and from php page send required message and success handler trap the output , display that to asp.net page.
EDIT
After checking your comment, you need to insert to mysql from asp.net. And that is pretty much doable. You need to have mysql connector for .net and use that library to make CRUD operation. Since answer or actual code snippet is not in scope of current question, i am posting links that will be helpful for you.
Following are some of link -
LINK1
LINK2

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

How to update Model from partial after ajax file upload?

So I have ajax file upload partial (using Jquery Form plugin), it's working perfectly, but I don't know to update model value after file uploading
<div>
#Html.Partial("PhotoUpload", Model.Place)
</div>
Here I'm calling partial and giving to it part of a model.
#model PlaceMap.DAL.Entities.Place
#using (Html.BeginForm("PhotoUpload", "Place", FormMethod.Post, new { #id = "photoUpload", enctype = "multipart/form-data" }))
{
{
#Html.ValidationSummary(true, "Image upload was unsuccessful")
#Html.HiddenFor(m => m.Photo)
<input type="file" id="file" name="file"/>
<input type="submit" id="sbm" />
}
}
This is view code of partial, accepting model and form for uploading
var options = {
url: "/Place/PhotoUpload",
dataType: "json",
clearForm: true,
resetForm: true,
success: showResponse
};
function showResponse(responseText, statusText, xhr, $form)
{
$('#photo').append('<img src="/Images/Places/' + responseText.Photo + '" />');
}
$('#photoUpload').submit(function ()
{
$('#photoUpload').ajaxSubmit(options);
return false;
});
Javascript code for plugin
[Authorize]
[HttpPost]
public ActionResult PhotoUpload(string Photo, HttpPostedFileBase file)
{
try
{
using (var ms = new MemoryStream())
{
//some logic here
return Json(new { Photo = filename });
}
}
catch (ArgumentException)
{
}
return PartialView();
}
Controller action code. It's returning file name, it's going to js function "showResponse" and appending image to div. It's all work perfectly, but I have to write file name to #Model.Photo of this partial and I don't know how to do it. Any suggestions?
One possibility is to use text/plain from the server:
return Json(new { Photo = filename }, "text/plain");
and on the client manually parse:
function showResponse(responseText, statusText, xhr, $form) {
var data = $.parseJSON(responseText);
$('#photo').append('<img src="/Images/Places/' + data.Photo + '" />');
}
Obviously you lust remove the dataType: 'json' option for this to work.
Another possibility is to follow what's explained in the documentation and write a custom action result which will wrap your JSON response with the <textarea> tags:
Browsers that support the XMLHttpRequest Level 2 will be able to
upload files seamlessly and even get progress updates as the upload
proceeds. For older browsers, a fallback technology is used which
involves iframes since it is not possible to upload files using the
level 1 implmenentation of the XMLHttpRequest object. This is a common
fallback technique, but it has inherent limitations. The iframe
element is used as the target of the form's submit operation which
means that the server response is written to the iframe. This is fine
if the response type is HTML or XML, but doesn't work as well if the
response type is script or JSON, both of which often contain
characters that need to be repesented using entity references when
found in HTML markup.
To account for the challenges of script and JSON responses when using
the iframe mode, the Form Plugin allows these responses to be embedded
in a textarea element and it is recommended that you do so for these
response types when used in conjuction with file uploads and older
browsers. Please note, however, that if there is no file input in the
form then the request uses normal XHR to submit the form (not an
iframe). This puts the burden on your server code to know when to use
a textarea and when not to. If you like, you can use the iframe option
of the plugin to force it to always use an iframe mode and then your
server can always embed the response in a textarea. But the
recommended solution is to test for the 'X-Requested-With' request
header. If the value of that header is 'XMLHttpRequest' then you know
that the form was posted via ajax.

PageMethods in ASP.NET failed to work if you have ASP.NET Routing Implemented

I have a web method:
[System.Web.Services.WebMethod]
public static string getCharacterstics(int product_id, int lang_id)
{
// code goes here...
}
I want to access it using PageMethods like:
(Provided the condition that i have Enable PageMethods in ScriptManager):
<script type="text/javascript">
$(document).ready(
function () {
$('#characterstics').html("loading");
// '<%= product_id_property %>' , '<%= this.LanguageID %>'
PageMethods.getCharacterstics(0 ,0 , OnSave);
}
);
function OnSave(result) {
}
</script>
I get the error "the http verb post to access path.. is not allowed"
I googled it and search the SO too but does not get any solution regarding to it Based on ASP.NET Routing.
What i believe is that because of asp.net routing the service methods are not accessible.
In addition i think i cannot even use JSON because of asp.net routing too.
Any help is appreciated.
Updated:
If i run the page with this url:
http://localhost:2606/searchdetail.aspx
The web method executed successfully.
Now
I have routing like this:
routes.MapPageRoute("searchdetail", "searchdetail/{ID}", "~/searchdetail.aspx");
routes.MapPageRoute("searchdetail", "searchdetail", "~/searchdetail.aspx");
The set_path() will work only for case 2 i.e without ID but does not work with case 1
if i try
http://localhost:2606/searchdetail
It works fine
but if i try to use:
http://localhost:2606/searchdetail/123
It gives error that object expected.
So set_path() is the option what should i write.
Currently, WebMethods don't work transparently with the Routing framework. There is a work around. You have to access the PageMethods directly by doing the following in your javascript:
PageMethods.set_path('/the/path/to/your/page.aspx');
PageMethods.YourMethod(params, onSuccess, onFailure);
I hope this helps.
I kept running into this myself. With routing enabled, if I added a value to the path, it would start to fail again. This solution is a bit of a hack, but it seems to be working consistently.
Create a server control hyperlink where the navigate url refers to itself, then once the control renders, grab the href and use it for set_path
This gets around the issue of set_path not referring to the correct location if you called
<asp:HyperLink ID="hlPage" runat="server" NavigateUrl="~/user.aspx" ClientIDMode="Static"></asp:HyperLink>
<script>
$(document).ready(function () {PageMethods.set_path($('#hlPage').attr('href'));})
</script>

How do I pass a list from aspx to javascript?

I have a list that I loop through to populate my table. I would like to pass a row of data to my javascript code at best. If not, I would like to pass the list and the id number to search for that row in the list. How can I do this?
<%foreach(var item in Model.NewList) { %>
<tr>
<td><%=item.EntryDate.ToShortDateString() %></td>
<td onmouseover="showDetailsHover(<%=item %>,<%=item.idNumber%>);"
onmouseout="hideDetailsHover();"><%=Html.ActionLink(item.idNumber,"SummaryRedirect/" + item.idNumber) %></td>
</tr>
<% } %>
You can use Json serialization to pass this data
http://json.codeplex.com/ - library for serialization
The concept of "passing a list from aspx to javascript" is a little hard to understand since your ASP.NET code runs on the server and javascript code runs in the browser. Because they exist in different domains, you can't simply "pass" a list from one domain to the other.
However, you have several options available:
Expose a web service that you can access from javascript. The web service can be responsible for providing the row of data so that javascript can understand it.
Put staticly formatted JSON data directly into your javascript function when your page loads. JSON is a format that javascript can understand. While technically this isn't "passing" a variable into a javascript function from ASP.NET, it is saying "Here's the data I want to run in my javascript function when/if it runs on the client."
The quickest way I can think of is this:
Use Json.Net to serialize your list as json string on your page.
Include jQuery and jQuery-json plugin.
Define a javascript list in a javascript function.
Something like this on your aspx page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.js"></script>
<script type="text/javascript">
function foo() {
// This is where we use the Json.Net library
var rawJsonString = '<%= Newtonsoft.Json.JsonConvert.SerializeObject(Model.NewList) %>';
// This is where we use the jQuery and jQuery-json plugin
var list = $.evalJSON(rawJsonString);
// Do stuff with your list here
}
</script>
THanks for the ideas. I eventually dug a little deeper with your suggestions and I used a for loop on the list I passed then add my data to the row based on the loop...
success: function(data) {
var loopList = data.message.NewList;
for (var i = 0; i < loopList.length; i++) {
addRecentData(loopList[i]);
}
},
});
function addRecentData(data) {
....
}
THanks for the nudge!

Categories