0

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?!

Ahmed ilyas
  • 5,502
  • 8
  • 37
  • 68

1 Answers1

1

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/

Morten OC
  • 1,754
  • 2
  • 23
  • 26
  • thanks. but it is never "bad" to have script code in a onclick - the code you supply does the SAME thing except is JQuery but attaches the event to the specified control... same thing as the onclick function – Ahmed ilyas Aug 30 '14 at 17:28
  • 1
    @Ahmedilyas yes I know it does the same thing, but its not good practice to bind your js stuff in onclick. See more here: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript and http://stackoverflow.com/questions/12627443/jquery-click-vs-onclick – Morten OC Aug 30 '14 at 20:14