PartialView is not updating with new data - asp.net

By default I am loading all data inside partial view
html code in Index.cshtml
#model GMWUI.ViewModel.MessageDisplayModel
<div id="divTblMsg" class="grid-content">
#{
Html.RenderPartial("filterMessages", Model);
}
</div>
HomeController.cs
public async Task<IActionResult> Index()
{
messageDisplayModel.Messages = await ApiClientFactory.Instance.GetMessages();
return View(messageDisplayModel);
}
when user click on filter button with search criteria
I am getting filtered data from web api to my home controller filtermessage method
here is my ajax call when I click filter button
$.ajax({
method: 'post',
url: "Home/postMessage",
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//my table element id is divTblMsg
$("#divTblMsg").html(data);
}
});
HomeController.cs
[HttpGet]
public async Task<IActionResult> filterMessages(GetMessageParams searchCriteria)
{
//I though adding below line will clear old data should update partial view with filtered data, but it is not working.
messageDisplayModel.Messages = Enumerable.Empty<Messages>();
messageDisplayModel.Messages = await ApiClientFactory.Instance.GetMessages(searchCriteria);
//I am getting filtered data to messageDisplayModel.messages and I am passing it to partial view
return PartialView("filterMessages", messageDisplayModel.Messages);
}
I was unable to find the issue

Is it by chance because your AJAX method is posting to Home/postMessage and not geting from filterMessages which you have marked with an [HttpGet] filter?

I fixed the issue by updating my ajax call as follows.
$.ajax({
method: 'GET',
url: '#Url.Action("filterMessages", "Home")',
async: true,
cache: false,
data: model,
dataType: 'HTML',
success: function (data) {
$("#divTblMsg").html(data);
}
});
I have updated Method to Get as I am using Get attribute for my action result and updated url and dataType to HTML because the response that we will get is in HTML.

Try changing URL path to match exactly as controller action name, and the method type equals to attribute set on that action:
$.ajax({
method: 'GET', // or type: 'GET'
url: '#Url.Action("filterMessages", "Home")',
data: JSON.stringify({ searchCriteria: model }), // here you should include action parameter name
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#divTblMsg").html(data);
}
});
If you want to use POST method, simply replace [HttpGet] with [HttpPost] and follow the URL convention as shown above.
Also take note that you should make sure that passed model contains object (an object defined like var model = {};) and then assign values for model properties.

Related

call a static method in User Control from js or ajax

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found
If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

The action method is fired, but value of the passed parameter is null

I use ASP MVC 5.
I try to send data from client to action method on the server.
Here is data that I sent:
var layer = {
layeType:"Vector"
layerName:"aaaa"
mapId:5
}
And here is ajax method:
function saveLayer(layer, callback, error) {
return $.ajax({
url: '/Mobile/Layer/SaveLayer',
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { layer: layer },
success: callback,
error: error
});
Here is action method:
public JsonResult SaveLayer(string layer)
{
return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}
The action method is fired, but value of the layer is null.
Any idea why value is null and how to fix it?
Ok,
Firstly, you are trying to send a complex object through on a GET request. GET requests don't have a body, they are limited to transferring data through the Url, so it would need to be a query string parameter.
Secondly, following rest conventions, GETs are idempotent, in that, each action should not have a side effect, calling it repeatedly should yield the same result.
I would switch your method to a POST, as that will more accurately convey that you are going to be causing a side effect on the server.
After you have done that, I would make a model in C# that matches the json structure that you are passing in, then you will get a value through.
Class
public class Layer
{
public string LayeType {get;set;}
public string LayerName {get;set;}
public int MapId {get;set;}
}
Javascript
function saveLayer(layer, callback, error) {
return $.ajax({
url: '/Mobile/Layer/SaveLayer',
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { layer: layer },
success: callback,
error: error
});
Function
public JsonResult SaveLayer(Layer layer)
{
return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}
That should sort it
First -
Make the type from GET to POST
Second -
Change the parameter type from string to Object type, i.e. Layer
The properties in Layer class should match the json data you are sending.
public JsonResult SaveLayer(Layer layer)
{
return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}

How do I fill a Javascript var with Json data from a Controller in Asp.net Core

I have a controller that returns a JsonResult
[HttpGet]
public JsonResult ShopMarkers()
{
var shops = repository.Shops;
return Json(shops);
}
In my view I'd like to fill a var with the data from that method. In an older MVC project I remember I'd write an ajax call to fill the var. Something like this:
var markers;
$.ajax({
type: 'POST',
url: '/Map/ShopMarkers',
dataType: 'json',
contentType: dataType,
data: data,
success: function (result) {
markers = result;
}
});
Or I could return a string to a view and Json.Parse it there inside a script tag.
Neither of these seem right. Is there a better way to fill my var in .Net Core?
Your client code is currently making the ajax call with POST type request. But your action method is decorated with HttpGet. So you should be getting a 404 error (If you inspect your browser dev tools, you should be able to see the status of the network (ajax) call)
[HttpPost]
public JsonResult ShopMarkers()
{
var shops = repository.Shops;
return Json(shops);
}
This should work assuming your code inside ShopMarkers method is not crashing ! (throwing any exceptions or so)
In your client side code you are trying to send an object. If you are sending a complex object, you should specify the contentType as "application/json" and send the data using JSON.stringify method.
var dataType = "application/json";
var data = { userId: 12, Password: 'ss' };
$.ajax({
type: 'POST',
url: '/Home/ShopMarkers',
dataType: 'json', // not really needed in your case
contentType: dataType,
data: JSON.stringify(data),
success: function (result) {
var markers = result;
console.log(result);
//Use result only here. Not outside
}
});
Since the ajax call is sending data in the request body, you should decorate the method parameter with [FromBody] attribute so that model binder will be able to map the posted data (from the request body) to your parameter.
[HttpPost]
public JsonResult ShopMarkers([FromBody] YourUserViewModel model)
{
//to do : Return some JSON
}

how to use jQuery ajax with asp.net user controls?

I want to use ajax with asp.net user control,
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: "{id:'" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
});
.cs code
[WebMethod]
public static string InsertTCSection(string id)
{
string result = "deneme";
return result;
}
You cannot call a method kept inside a usercontrol through jquery.
because .ascx controls don't represent real url.
They are meant to be embedded in some ASP.NET page, hence they don't exist at runtime.
what you might do is, to create a separate service and place your method there.
like webservices.
see this, this and many others
i am using generic Handler to solve this problem.
Try:
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: JSON2.stringify({ id: id}, //Your 2nd id is passing value but i dont know where its come from
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
}
)};
and in cs:
[WebMethod]
public static string InsertTCSection(string id)
{
string result="deneme";
return result;
}
I think you might be missing this attribute
[System.Web.Script.Services.ScriptService]
Before you service class as
[System.Web.Script.Services.ScriptService]
public class TCSection: System.Web.Services.WebService
{
[WebMethod]
public static string InsertTCSection(string id)
{
}
}
Or there may be one other reason that path of the webservice is not right.

converting object variable to json string for asp.net page method

This is probably a very simple task to perform but I'm taking the risk to ask anyway.
I have an object variable that looks like this:
var MyObj = {"Param1": "Default",
"Param2": "test",
"Param3": 3 };
I'm using ASP.net and I'm looking to pass this object to a page method via jquery.
So far, I have this javascript code:
function LoadObject () {
var TheObject = MyObj.toString();
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: TheObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
I have a page method set up in the .cs file and I put a breakpoint in it but it never gets there; nothing happens.
Please let me know what changes I need to make to get this to work.
Thanks.
You need to serialize TheObject into a JSON string, and ensure that the GetCount method accepts an object with the same signature as TheObject.
I use the jQuery.JSON library to do this so that my syntax becomes:
data: "{ methodParameterName: " + $.toJSON(TheObject) + " }"
I use this library, but you can acheive the same thing with any other library in a similar manner
The first thing that you need to know is that you need to match your method name with your url
for example if your method on your code behind is named "calculate", your url must be something like this "../Pages/TestPage.aspx/calculate"
other thing that you need to keep in mind is the parameters of your method, the names and the types of your parameters must match in you ajax call and your method (code behind)
if the sign of your method is something like this
[WebMethod]
public void Calculate(string data){
// your code here
}
Your ajax call must be like this:
function LoadObject () {
var objetoJson = {
data: JSON.stringify(MyObj)
};
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/Calculate",
data: objetoJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
This section is so important:
var objetoJson = {
data: JSON.stringify(MyObj)
};
the name "data" is the name of your parameter in your method (code behind) and "JSON.stringify" is a helper functions already defined on your browser to convert and object to string
Hope this helps
Take a look at this thread: JSON stringify missing from jQuery 1.4.1?
Abstract: jQuery doesn't have a native method to do it. But there are many plugins out there.
EDIT
Sample C# code receiving your JSON object:
[WebMethod]
public static int GetCount(GetCountParams p)
{
// ... Do something with p.Param1, p.Param2, etc.
return 0;
}
public class GetCountParams
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
EDIT 2
Sample jQuery AJAX call using that object as parameter:
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: "{ p: '" JSON.stringify(MyObj) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

Resources