I have used cross domain to call one domain to another as below ,
My ajax call from mvc project as done below,
var tableparameter = '{TableName: "' + $("#tableOneTableName").val() + '" }';
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/onchangetableone",
data: tableparameter,
success: function (response) {
alert("hi");
}
});
Then i added below code in web.config file within web api project as below,
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
Then i written action as below,
[HttpPost]
[Route("api/ajaxapi/onchangetableone")]
public List<DropDownListValuesForQuery> OnChangeTableOne(TableNameFormCustomFilters TableParameter)
{
CaseModel query = new CaseModel();
List<DropDownListValuesForQuery> listValues = new List<DropDownListValuesForQuery>();
listValues = query.GetColumnNames(TableParameter.TableName);
return listValues;
}
And list values as below,
public class TableNameFormCustomFilters
{
public int TableName { get; set; }
}
Here i can access the webapi source using cross domain but the parameter value not come from script. Please give your suggestion.
Thanks in advance.....
change your javascript obj little bit ,
var TableParameter =
{
TableName: $("#tableOneTableName").val()
};
Ajax
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/onchangetableone",
data: TableParameter ,
success: function (response) {
alert("hi");
}
});
' TableParameter ' must be same as model parameter
Check below code :
var TableParameter = { "TableName": $("#tableOneTableName").val() };
$.ajax(
{
url: 'http://localhost:55016/api/ajaxapi/onchangetableone/',
type: "POST",
async: false,
contentType: "application/json;",
data: JSON.stringify(TableParameter),
success: function (result) {
alert("hi");
}
});
Cheers !!
Related
In my project I send post json data object. One item of this object is base64 string. When base63 string is too long, my request doesnt reach to controller. In my opinion , due to length of parameter,it doesnt work. I couldnt find any solition.
[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Page item)
{
if (item == null
|| string.IsNullOrEmpty(item.Title)
|| string.IsNullOrEmpty(item.SeoUrl))
return Content(Serialization.JsonSerialize(new { Status = 400 }));
return Content(Serialization.JsonSerialize(new { Status = 200, Result = PageRepository.Add(item) }));
}
In controller , I wrote code above, in view I wrote code below
var item = {
Title: title,
SeoUrl: seo,
IsActive: isActive,
Portals: portals,
Content: content,
Lang: pageLanguage,
IsShown:isLock,
MetaKeywords:keywords,
MetaDescription:description
}
$.ajax({
type: 'POST',
url: '#Url.Action("Add", "Page")',
data: JSON.stringify(item),
success: function(data) {
if (data.Result !== "SUCCEED") {
if (data.Result == "SEO_URL_EXISTS") {
toastr.warning('Böyle bir seo_url mevcuttur !!!');
return;
}
toastr.error('#Resources.Resource.Error_Unexpected');
return;
}
if (!isActive) {
toastr.success('#Resources.Resource.Success_PageSave');
return;
}
toastr.success('#Resources.Resource.Success_PageSaveAndPublish');
return;
},
error: function(error) {
toastr.error('#Resources.Resource.Error_Unexpected');
return;
},
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function() {
waitingDialog.show('#Resources.Resource.Waiting_PageUpdating');
},
complete: function() {
waitingDialog.hide();
}
});
In web config I added below,
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="999999999"/>
</webServices>
</scripting>
</system.web.extensions>
content item may include base64 string. How can I send this jason data to controller, even there is long base64 string.
This is error:
Error during serialization or deserialization using the JSON
JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength property. Parameter name: input
function GetUserEditProfileDetails() {
var res = {};
res.ID = parseInt($("#User_ID_EditProfile").val());
res.FirstName = $("#FirstName").val();
res.LastName = $("#LastName").val();
res.EmailId = $("#EmailId").val();
res.Mobile = $("#Mobile").val();
res.ProfilePic = $(".ProfilePic").attr("src");
return res;
}
$.ajax({
url: "Profile/UpdateUser",
async: false,
type: "POST",
data: GetUserEditProfileDetails(),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
alert(JSON.stringify(jqXHR) + "-" + textStatus + "-" + errorThrown);
}
})
By using above code, I am trying to save the details of a user. But when the profile pic is too long then the controller method is not calling and it shows internal server error.
Hi Please check below solution :
You need to change maxAllowedContentLength in Web.Config File :
In system.web :
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
And in system.webServer
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
Cheers !!
I am trying to call data from the following host url test.domain.com/test2.aspx/BindDatatable, however i keep getting 404 response and the following message in my console window:
error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.domain.com/test2.aspx. This can be fixed by moving the resource to the same domain or enabling CORS
i have added the following cors header in the web.config file of my host(url ) file:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="origin" />
<add name="Access-Control-Request-Method" value="POST" />
<add name="Access-Control-Allow-Headers" value="content-type, accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
it also contains the following web-method behind test2.aspx.cs:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod()]
public static string BindDatatable()
{
DataTable dt = new DataTable();
List<UserDetails> details = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["#####"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("######", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Name= dtrow["###"].ToString();
user.Loan = dtrow["###"].ToString();
user.Evnt = dtrow["###"].ToString();
details.Add(user);
}
}
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(details);
}
ajax function called from corsTest.aspx
$(document).ready(function () {
$.support.cors = true;
$.ajax({
type: "Post",
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://wwww.test.domain.com/test2.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.toSource());
console.log(data);
var myData = JSON.parse(data.d)
for (var i = 0; i < myData.length; i++) {
$("#tbDetails").append("<tr><td>" + myData[i].Name + "</td><td>" + myData[i].Loan + "</td><td>" + myData[i].Evnt + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
I am not sure, what else i am suppose to update further to get this to work. Do I also need, to define the cors header in the head tag of the text2.aspx page as well.
thanks in advance for any further feedback/guide.
I stuck into similar situation today so sharing my solution, hope it could help somebody. I used jsonp to fetch the data from cross domain. Taking your example, if one has access to BindDatatable() method in test2.aspx.cs, then we can modify json object to be returned in the format like jsonData({..your json..}). By wrapping the method with jsonData(), it could be read by jsonp during ajax call made like:
var url = "http://wwww.test.domain.com/test2.aspx/BindDatatable";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'jsonData',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Otherwise as suggested in the above post, you can create a function in your own application corsTest.aspx.cs and access cross domain link through it in C# and return json as shown below:
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "/corsTest.aspx/BindDatatableTest",
dataType: "json",
.
.
error: function (result) {
alert("Error");
}
});
Define function in corsTest.aspx.cs like:
private string BindDatatableTest()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string url = "http://wwww.test.domain.com/test2.aspx/BindDatatable";
WebClient wc = new WebClient();
ServicePointManager.Expect100Continue = false;
ServicePointManager.MaxServicePointIdleTime = 2000;
string json = wc.DownloadString(url);
object jsonData = new
{
jsonFinal = jsonD
};
return Content(serializer.Serialize(jsonData), "application/json");
}
Also, in order to call cross domain url you have to add the following code to web.config:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
Check if the remote method is available. Check the firewall of the server where the service is hosted if it allows connections for the specific port. Also check on your machine if output port is not blocked.
Another way to enable cors is to make the connection on the server side.
For instance you can add service reference to the remote method and use that method on the server side in your local project. Then on the client you have to call only the local method that is within your solution and you don't have to enable cors on the client.
I don't get why $.ajax() function cannot reach my [WebMethod].
Here is the jQuery below:
$('.BasketUpdaterSubmit').click(function() {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
Here is the C# code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string UpdateAsyncBasket(string name)
{
// random stuff
return "Received : \t " + name;
}
When I place a breakpoint on the return statement I never seem to get there.
What am I doing wrong?
Based on the experience I've had with this stuff, I THINK the JS has to be put inside inside .NET's page load javascript function to access C# web methods.
function pageLoad(sender, eventArgs) { }
Try a GET instead of a POST. I have a few web methods that work fine using similar javascript, but have decorated the method with this instead of just [WebMethod]:
[WebMethod, ScriptMethod(UseHttpGet = true)]
And then make sure your ajax call specifies GET:
$('.BasketUpdaterSubmit').click(function() {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
Try this code,
$(document).on("click",".BasketUpdaterSubmit",function(){
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
});
And the web.config you have to add following section inside the system.web section
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Above code should work(tested in my machine). My best suggestion for you is create a web service for this. so you can omit the page life cycle.
You can refer following sample to learn how to do it properly
http://tutorials.cmsnsoftware.com/2011/01/how-to-call-csharp-function-in-ajax.html
We figured out what's going on.
It seems that there is a default ajax setup function which was interfering with my jquery function and didn't proceed when testing. Most probable reason is improper parameter handling.
Sorry for the late response. Thank you all.
my jquery ajax function is not calling webmethod. jquery function return webservice page's html.
function is not understand "ebulten_add" is a webmethod!
"url:ajaxPage.aspx/e_bulten"
to write webmethod name or not write is same.. both of return ajaxPage.aspx html.
$.ajax({
type: "POST",
url: 'ajaxPage.aspx/ebulten_Add',
data: "{ebEmail:'" + Ebemail + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$("#span_result").hide();
$("#span_spinner").hide();
$("#span_result").html(result.d).fadeIn();
},
error: function (msg) {
$("#span_result").hide();
$("#span_spinner").hide();
$("#span_result").html("Lütfen tekrar deneyin.").fadeIn();
}
});`
web method in ajaxPage.aspx
[System.Web.Services.WebMethod]
public static string ebulten_Add(string ebEmail)
{
if (ebEmail == "Email")
{
return "*Bilgilerinizi Girmediniz";
}
else
{
List<ListItem> ebList = new List<ListItem>();
ebList.Add(new ListItem("#Eb_email", ebEmail));
BL.Atom.GetByVoid("spEbulten_Add", ebList);
return "*E-Bülten kaydınız başarıyla tamamlanmıştır";
}
}
As I can see, you are returning string not json
so just update your dataType: 'text' and it should be ok
Agree with #SenadM. Either change the dataType:text or return JSON from your webmethod:
[System.Web.Services.WebMethod]
public static string ebulten_Add(string ebEmail)
{
if (ebEmail == "Email")
{
return "{ \"response\": \"*Bilgilerinizi Girmediniz\"}";
}
else
{
List<ListItem> ebList = new List<ListItem>();
ebList.Add(new ListItem("#Eb_email", ebEmail));
BL.Atom.GetByVoid("spEbulten_Add", ebList);
return "{ \"response\": \"*E-Bülten kaydiniz basariyla tamamlanmistir\"}";
}
}
Also, make sure POST is enabled in your web.config:
<configuration>
<system.web>
<webServices>
<protocols>
<!-- <add name="HttpGet"/> --> <!-- uncomment to enable get -->
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
Just Change var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Permanent}; to var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Off}; This should solve the problem.