Reputation: 5822
So, here is a weird behaviour I have noticed today.
I have a controller which inherits from SurfaceController.
I have a [Post] Action method which returns back to the same partial view and that's fine. The reason is due to paging/filtering that happens on that page.
Now, on the view itself, if I use a button submit, I see everything being submitted just fine.
However, if I use a hyperlink with an onclick event to set hidden field values and then do a form.submit(), initially the model has values which are null but then it re-executes the submit with the all of the values put in place again!
That doesn't make sense. What is the difference with a button submit and a javascript function doing a form.submit() ?
There really isn't much code:
// Controller
[HttpPost]
public PartialViewResult FilterResultsForTransaction(MyModel model)
{
.....
}
// View
<script language="javascript">
function ApplySort(fieldname, sortDir)
{
$('#Filter_FieldName').val(fieldname);
$('#Filter_SortDir').val(sortDir);
//var form = $('#form');
//form.submit();
}
</script>
<snip>
<input type="submit" onclick="javascript:ApplySort('OrderDate'........)" value="ASC" />
ASC
Now, if I don't use the submit button but just the hyperlink and comment in the form.submit() in the JS function - it does the post but the model values are null/default and then it recalls itself with the values populated again.
thoughts?!
Upvotes: 0
Views: 1513
Reputation: 1784
When you click on the submit button, the page will submit its data BEFORE the script in ApplySort() is complete. So you will have to stop the submitting, then set your hidden field values, and then submit the form. Like this:
<input type="submit" data-field="bla" data-sort="ASC" value="Sort ASC" />
<script>
$("input").on("click", ApplySort)
function ApplySort(e)
{
e.preventDefault(); //stop postback
var btn = $(this);
var form = $('#form');
$('#Filter_FieldName').val(btn.attr("data-field"));
$('#Filter_SortDir').val(btn.attr("data-sort"));
console.log("submit")
form.submit();
}
</script>
Its generally bad to have script code in a onclick, so I bind the click event in my js code with jQuery. Test it out here: http://jsfiddle.net/03gj1r02/2/
Upvotes: 1