Conditionally resetting input element value before submitting form to MVC3 action
this is probably a simple question but I'm new to jQuery with MVC3. I have an MVC3 application where an Index action lists some papers with their authors. Users can filter the list by (among other parameters) author name, so I have an input element using jQueryUI autocomplete to let them type some letters and pick the desired author. When this happens my JS code stores its ID into a hidden element and posts the form; the ID is then passed via the model binder to an object representing all my filters.
The filters object is like:
public sealed class PaperFilter
{
public int? AuthorId { get; set; }
// ... other params here
}
The controller action receives page number and sort parameters (the view uses the MvcContrib grid) and this filter. It then creates a view model including the list of papers and a number of properties representing the filter properties, and passes it back to the view:
public ViewResult Index(int? page, GridSortOptions sort, PaperFilter filter)
{
var papers = _repository.GetPapers(filter);
if (sort.Column != null)
papers = papers.OrderBy(sort.Column, sort.Direction);
ViewBag.Sort = sort;
PaperIndexModel model = new PaperIndexModel(filter)
{ Papers = papers.AsPagination(page ?? 1, 10) };
if (filter.AuthorId.HasValue)
{
Author author = _repository.GetAuthor((int)filter.AuthorId);
model.AuthorName = author.FirstName + " " + author.LastName;
}
return View(model);
}
where the returned model contains the papers list together with a copy of the filter properties.
The view form relevant code is:
...
@Html.TextBoxFor(m => m.AuthorNa开发者_开发问答me)
@Html.HiddenFor(m => m.AuthorId)
...
and its JS code:
<script type="text/javascript">
$(function () {
$("#AuthorName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Author/FindAuthor", type: "POST", dataType: "json",
data: { LastName: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.FirstName + ' ' + item.LastName, value: item.LastName, id: item.Id };
}));
}
});
},
select: function (event, ui) {
$("#AuthorName").val(ui.item.value);
$("#AuthorId").val(ui.item.id);
$(this).closest("form").submit();
}
});
});
</script>
This works fine, anyway I'd like my users to reset the author filter by simply clearing the input box (AuthorName) and pressing enter; but to do this I'd need to reset the AuthorId value, i.e. do something like $("#AuthorId").val("") before the form is posted. I tried to do this on keypress but it does not seem to fire before the post happens, because my action still gets the filter with its AuthorId populated. Could anyone suggest a solution?
check it right before your .ajax() call. If the length is 0 you don't have to .ajax either and just return.
精彩评论