Getting Max URL length exceeded c# MVC - c#

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 !!

Related

Parameter can't pass using ajax in Cross Domain

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 !!

How enable cors in ajax?

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.

Not geting expected data from jquery ajax call

Here is the c# web method
[WebMethod]
public string Hello()
{
return "Hello World";
}
Here is the jquery ajax code
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx",
dataType: 'text',
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::'+ rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: "+exception +"Status:: "+xhr.statusText);
}
});
But instead of getting Hello World in rtndata i'm getting the full html response page.
You need to return a json model or disable layout
If you receive an html page is because you are sending a html page.
You should double check your code to know if anything is append to the response before send the output.
Try to send a JSON formatted response to the ajax call like:
{'hello':'world'}
Then you add dataType as an option of $.ajax. If you want to print the output, you can do alert(JSON.stringify(response)).
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + JSON.stringify(rtndata));
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
There are an important thing... More times you add cache: false, but this does not work properly and you should do a trick to solve.
Add the timestamp as a parameter of the call like:
var date = new Date();
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx?timestamp="+date.now(),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + JSON.stringify(rtndata));
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
Hope this helps...
The html page you get is an overview of all the available webmethod in the servicer - an API of sorts. Try navigating to it in a browser.
If you want to call your Hello WebMethod you should add "/Hello" as the method name to the url:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://10.0.2.2/SampleService/Service/HelloWorld.asmx/Hello',
dataType: 'json',
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::'+ rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: "+exception +"Status:: "+xhr.statusText);
}
});
You can read more here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
You have to append the method name to the URL (/HelloWorld, for example) and specify method: "post" in your ajax call (if you want to use a POST request). Try this:
$.ajax({
url: "http://10.0.2.2/SampleService/Service/HelloWorld.asmx/HelloWorld",
method:"POST",
dataType: "text",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
If you want to use GET as the request method, make sure you have this tags in your web.config file:
<system.web>
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
Also, you need to decorate the service method with the ScriptMethodAttribute:
[ScriptMethod(UseHttpGet = true)]
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
The ajax call (method: "GET" is optional, as it is the default method for text):
$.ajax({
url: "http://localhost:57315/helloworld.asmx/HelloWorld",
method: "GET"
dataType: "text",
cache: false,
crossDomain: true,
timeout: 15000,
success: function (rtndata) {
alert('Got Success ::' + rtndata);
},
error: function (xhr, errorType, exception) {
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
As you are using cache: false, probably you want to use the GET request:
Setting cache to false will only work correctly with HEAD and GET requests.
It works by appending "_={timestamp}" to the GET parameters.

jQuery Ajax() can't reach C# Webmethod

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.

jQuery Ajax not calling webmethod after url routing

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.

Categories

Resources