Posting to controller with jQuery
After reading some information I thought this should work. The JS function is called and jQuery animation is spinning, but the action is not posted to. As well开发者_Go百科 I will want the startDate and endDate to be provided from text inputs but for now even hard-coded is not working. Thanks everyone!
Controller:
public class NewsController : Controller
{
[HttpPost]
public ActionResult Search(string lang, string pageNumber, string startDate, string endDate, string search)
{
}
}
View:
@using (Html.BeginForm())
{
<a href="#" id="go_button">...</a>
}
<script type="text/javascript">
$('#go_button').click(function () {
$.post("/News/Search", { startDate: 'start', endDate: 'end'});
});
Make sure that the script is either located after the anchor in the DOM or wrap in a document.ready
:
$(function() {
$('#go_button').click(function () {
var url = '@Url.Action("Search", "News")';
$.post(url, { startDate: 'start', endDate: 'end' }, function() {
alert('success');
});
return false;
});
});
This should work, at least it should invoke your action. What this action does, whether it throws an exception or something is another matter, but at least you should get into it and have the startDate
and endDate
parameters properly assigned:
public class NewsController : Controller
{
[HttpPost]
public ActionResult Search(string lang, string pageNumber, string startDate, string endDate, string search)
{
return Json(new { success = true });
}
}
$.post will only post the request to the server - it won't automatically update your page with your view.
You need to include a success function which you then use to insert the View into the DOM.
e.g.
try something like this in the jquery
$(function() {
$('#go_button').click(function () {
var url = '@Url.Action("Search", "News")';
$.post(url, { startDate: 'start', endDate: 'end' }, function() {
$('#result').html(data);
});
return false;
});
});
This will post to your action and put the returned view inside an element with the ID 'result'.
You should have your action return a PartialView, if you don't the Layout to be included.
精彩评论