Is there any way to update instance variables from a page method without making them static?
My page has a ViewModel object that contains lots of data that I would like to update ajax and pagemethods. I use the ViewModel in the asp.net front-end page to print out variable values.
ViewModel Class
// ViewModel class
public class ItemViewModel
{
public List<Item> Items = new List<Item>();
}
** ASP.net webforms page (backend)**
public ItemViewModel ViewModel;
protected void Page_Load(object sender, EventArgs e)
{
// init ViewModel;
}
[WebMethod]
public static bool GetItems(string userId)
{
// lots of code...
ItemService i = new ItemService();
ViewModel = i.GetItems(userId); // How to update page variables or pass in a new one?
return true;
}
Front-end
<ul>
<% foreach (Item i in ViewModel.Items)
{ %>
<li>
<%=i.ItemName %>
</li>
<% } %>
</ul>
Using Session state is possible as it is carried over multiple pages, but you will have to make sure that when a user switches a pages at any given time, the Session-data is cleared because else it will be used on next pageload (unless that is what you want).
You could also have your method build a htmlstring that is pasted into your page:
public string myFunc()
{
string html = "<li>foo</li";
html += "<li>foo2</li>";
return html;
}
And then in your ajax success
callback you can do:
success: function(data) {
$("#myUL").html(data);
});
It works, but it does require you to build a html string by hand, which gets exponentially harder if you have to handle more than a onedimensional array.
I would suggest using JSON in combination with Ajax. It's the easist way to pass whatever you want, and still be able to handle the data rather than just have it pasted as html.
http://www.learn-ajax-tutorial.com/Json.cfm
I would suggest reading through this tutorial, it gives you a good idea on how JSON is built and handled.