I work with asp.net and I have some issues.
I created partial view with error message and I want to call view using jQuery.
I have already created function in controller which returns a partial view. But I am stuck with ajax, all time I get errors.
Controller:
[HttpGet]
public ActionResult LoadPartialView()
{
return PartialView("_ErrorMessageWindow");
}
jQuery:
$.ajax({
url: "#(Url.Action('LoadPartialView'))",
type: "GET",
cache: false,
datatype: 'html',
success: function (data) {
}
});
Error:
jquery-3.3.1.min.js:2 GET https://localhost:5001/#(Url.Action('LoadPartialView'))?_=1565937416181 404 (Not Found)
Reason for not working:
#Url.Action() is Razor server side code and that will not be parsed in external .js files.
Solution:
Create this <div> in your .cshtml:
<div id="partial-view-url" data-request-url="#Url.Action("LoadPartialView", "ControllerName")"></div>
then get Partial View Url in your separate/external .js file using data-request-url like below:
$("#partial-view-url").data('data-request-url');
So your $.Ajax will become like this:
$.ajax({
url: $("#partial-view-url").data('data-request-url'),
type: "GET",
cache: false,
datatype: 'html',
success: function (data) {
}
});
Another way is to declare global variable:
Create global variable in your main .cshtml file and use it in your external .js file.
//Declare this variable in your main `.cshtml` file.
var partial-view-url = #Url.Action("LoadPartialView","ControllerName");
//and then use it in your separate/external `.js` file.
$.ajax({
url: partial-view-url,
type: "GET",
cache: false,
datatype: 'html',
success: function (data) {
}
});
Related
I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....
I've implemented the following code within my MVC controller
[HttpPost]
public string tt(string o)
{
return o;
}
[HttpPost]
public string tt2(string o)
{
return "lala";
}
And I'm triggering the following ajax calls from the browser
$.ajax({
url: "/Home/tt2",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
$.ajax({
url: "/Home/tt",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
As a result when running the first ajax call the result is
lala correct
And for the second ajax call, the result is
undefined correct
In the mean time these are some stuff I tried
Adding dataType: "json", to the ajax call
Changing the string data from {o: 'asdas'} to 'asdas'
Removing the JSON.stringify
Adding the charset=utf-8 to the contentType
Changing the ajax call type and MVC controller method from POST to GET to PUT
Changing the MVC controller method parameter from string to int
Removing the error method from the ajax call
Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})
I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..
Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..
Any thoughts on how to make ajax call work?
try:
[HttpPost]
public string tt([FromBody]string o)
{
return o;
}
Your request should be like this:
$.ajax({
url: '#Url.Action("tt", "Home")',
data: {
"o": "asdasdas"
},
cache: false,
type: "POST",
success: function (response) {
},
error: function (xhr) {
}
});
I need a little help.
So I'm trying to call a lot of partial views from the same list model, each using a different filter. Is there anyway for me to pass the Datafilter value from the views into the model?
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "ControlerFolder/Controler",
data: {someParameter(Filter): "value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
msg is the json that you can return
}
});
});
});
If you need more help say something.
I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.
Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})
I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`
I created a project in Visual Studio named 'MyProject', and Added .aspx file to it named 'MyPage.aspx'.
In 'MyPage.aspx.cs', there is a web method as shown below
[WebMethod(EnableSession=true)]
public static string GetDetails()
{
try
{
var data= HttpContext.Current.Session["mySession"] as myDto;
return myDto.Username;
}
catch
{
return "Sorry";
}
}
Now, I created another project in that same solution named 'NewProject'.
And I have a page in this project as 'NewPage.aspx', from which I am trying to call GetDetails() from 'MyPage.aspx' (MyProject).
So I tried the following code.
NewPage.aspx
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://localhost:2463/MyPage.aspx/GetDetails',
success: function (data) {
alert(data);
},
error: function (response) {
alert('Error');
}
})
});
</script>
but the Web Method isn't getting hit & I get the 'Error' alert displayed.
I also tried this
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2463/MyPage.aspx/GetDetails",
contentType: "application/json; charset=utf-8",
data: '{}',
datatype: "json",
success: function (msg) {
alert('success');
},
error: function (response) {
alert('Error');
}
});
});
</script>
but no luck.
Plz Help...!!
Sounds like a CORS problem.
By default you cant access a service that is not within the origin domain (scheme, hostname, port).
You have to make sure that link http://localhost:2463/MyPage.aspx/GetDetails is available while making jquery ajax call. For that
you can run MyProject in a seperate instance of VS and then run NewProject in another instance of VS.
Check console in inspect element and find a solution for given error.
You can call webMethod of another page. Your code seems correct.
And no need to write whole URL ('http://localhost:2463/MyPage.aspx/GetDetails') of a page, Just write 'MyPage.aspx/GetDetails'.
Been following some tutorials, as i'm learning C#, however was just attempting to make an ajax call to the server, i'm using my localhost.
As far as I can tell i'm doing its right, but it's obviously not.
Maybe it my folder structure or just the name of the file.
The Default.aspx file is at the project root
Here is my ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx",
dataType: "json",
data: "{'FirstName':'test','LastName':'test1','City':'test3','EmailID':'test4'}",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});
I know eventually it will have to call a method within the file, but its not even finding it at the moment.
Thanks in advance, James
You can use controller Home and create the one action.
Example:
public ActionResult FirstAjax()
{
return Json(true, JsonRequestBehavior.AllowGet);
}
After that your jquery ajax is:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "Home/FirstAjax",
dataType: "json",
data: "",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});