Reputation: 21
I have some app on asp.net mvc. And I am trying to create table filter. Page is very difficult, so i can't get data from JSON response. I am trying to get it via call action with params.
function refresh() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, null, "json");
}
<select id="list" onchange="refresh()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<%foreach (var i in (IEnumerable<int>)ViewData["list"])
{ %>
<%=i %><br />
<%} %>
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
ViewData["list"] = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
return View();
}
But I don't see new data. What's wrong? How I can refresh page?
PS I meen that i wanna go(redirect) from action A to action A(with param). I don't want reconstruct page on client side
Upvotes: 2
Views: 3851
Reputation: 532455
You aren't doing anything with the result you retrieve with the get
call. Also, since you're returning a view, you should set your data type to html
.
$.get('/Home/Index', params, function(html) {
$('body').html(html);
},'html');
I'd note that I would probably only replace the section that gets updated. You can do this by using a partial view to hold just that section, then when you get the request via AJAX you can return just the partial view instead of the full view. The other thing that I would do is make the views strongly-typed to IEnumerable<int>
and pass a model, instead of using view data.
View
<script type="text/javascript">
$(function() {
$('#list').change( function() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, function(html) {
$('#listResults').replaceWith(html)
}, "html");
});
});
</script>
<select id="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<% Html.RenderPartial( "ListResults" ); %>
Partial View
<div id="listResults">
<%foreach (var i in Model)
{ %>
<%=i %><br />
<%} %>
</div>
Action
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
var model = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
if (this.Request.IsAjaxRequest())
{
return PartialView(model);
}
return View(model);
}
Upvotes: 5
Reputation: 5461
I see one problem in the code above:
The $.get()
does not do anything when your request is complete(your data has been fetched from the server)
Instead of passing null there you should pass in a function with a parameter which is the data. Example:
$.get("/Home/Index"
, params,
function(data){
//do something with data.
//data is json object returned
}, "json");
in this function you can actually have your filter applied to the table
Upvotes: 1