How do I submit a form with a link in ASP.Net MVC? - asp.net-mvc

I have a HTML form, and I have a Controller Action that accepts the POST request. Everything works with a regular submit button, but I would like to submit the form with a link (<a>-tag) instead, to be able to further control the formatting. Is there any way of doing this nicely built into the ASP.NET MVC Framework, or should I write my own extension method? Is it even possible to do this without javascript (I will use AJAX in the future, but it has to work without).

Here is a complete example. Note that this particular example does something fairly important: it has a fallback for browsers with JavaScript disabled.

If javascript and jQuery is enabled this effectively replaces all submit-buttons with links:
$("input:submit").hide().each(function (index, Element) {
var elm = $(Element);
elm.after($("<a href=#>" + elm.val() + "</a>")
.click(function () { elm.click(); })
);
});
Based on post linked to in the accepted answer.

I'm not aware of a helper and as far as I know it is impossible to submit a form using an anchor tag without using javascript.

You cannot 'submit a form' using a link (<a> tag) without Javascript. The javascript is going to generate a standard POST request (same as clicking a submit form button) behind the scenes.
There are other workarounds for those with JS disabled, look at what #Craig Stuntz submitted.

Related

Ajax With JQuery MVC Form Posting

I'm a complete Ajax noob and I'm finding myself a little lost in how to best approach things, I've been looking over SO and found a post about Ajax that included this JavaScript:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
I incorporated this into my scripts file for a form on one of the pages in my site and quickly realised this actually attaches to ALL the forms, site wide including the login form.
I want to treat the login form as a special case and actually perform a redirect rather than simply insert the returned HTML fragment into an element on the page.
I'm presuming that replacing 'form' with the ID of the login form will differentiate the login form from 'general' form handling processes and was wondering what are the accepted best practices for this.
Do you have a 'general' Ajax hander like the one above or is it better to have specific JavaScript functions for each form depending on what they need to do with the response?
It sounds to me like you included something generic for a situation which should have been localized. In my opinion blanket approaches like this are not really desirable, especially not with something which is going to affect every form in your application.
The real meat of this to take away is the $.ajax code. Use ajax when you want, and use formal posting otherwise (which is default).
Using an exact reference will of course differentiate certain forms in your application, but this is something which should be done in a view's script, and not in one blanket script which is included application wide.
What I tend to do is use ajax when I want to provide a preview, or if I want to post without the user navigating away from the page.
Sometimes in rare occasions I will have a page which is replaced with a few sliding windows via ajax and then at the end of the series I will want to redirect. When that is the case, I will have my controller return a string which allows the view to redirect to that string in the success function of the ajax call.
I tend to keep mine separate, though others may do differently. They post to different URLs and do different things with the data.
I refer to the form by id:
$('#myformid")
You may wish to use the not equal selector if you just want to apply your function to all forms except your login form.
$('form[id!="loginform"]')...

Sending form contents as both html and ajax?

I have an admin form that updates a model via a html submit. I'd like to be able to send the form's contents to an Ajax modal dialog for a 'preview' via a link or button in the admin form.
Is there a way to send the form's contents to the modal dialog via Ajax without breaking the html submit? So far all I can do is get the data into the modal as html which breaks the js rendering. All the Ajax submit examples I find attach to the form which will break the html submit.
Suggestions and/or pointers are appreciated.
We are using Rails 3.2.12 for what it's worth.
I suppose it depends on how you are rendering your modal. If you're doing it server side and just need to get the form values to your ajax controller action you could do something like this with jquery"
$.post(ajaxUrl + "?" + $("#myform").serialize())
to generate a query string of your form values that you could sent to you ajax model.
Or if you're building the modal client side try
$("#myform").serializeArray()
to get an array of name, value pairs
This is what it took to get this to work under Rails 3.2.12
View:
<%= link_to 'Preview Promotion UI', admin_preview_promotion_url, id: :promotion_preview %>
The above link is inside the form do/end.
Javascript in application.js
$("#promotion_preview").live('click', (function (event) {
event.preventDefault();
$.post("/store/admin/promotions/preview",
$(event.currentTarget.parentElement).serialize().replace('=put&', '=post&'),
{},
"script"
);
}));
Rails.js injects some hidden code in the page that sets the type of response to PUT and then gets in the way of the routing. At least in this case simply replacing PUT with POST fixes things.
With this bit of code I can post my form updates as usual and activate a modal dialog "preview" using the form data.

Passing data between pages with jQuery Mobile?

So I've just started learning jQuery Mobile, and I've learned how it loads all links via ajax without actually loading the next page. Several of my pages use forms and GET to pass data on to the next page-- How can I do this while using jQuery Mobile?
One thing that I think is cool about JQM is that you don't have to use parameters to pass data between pages. Since you're in the same DOM as the first page, you can access data using plain old variables, i.e.
field1 = $('[name=field1]').val();
field2 = $('[name=field2]').val();
And so long as you're using the ajax feature of JQM you could do the following in the next page:
$('.title').text(field1);
I made a jsfiddle example for you.
Other ways would be to use the localStorage or sessionStorage api or there are also some plugins mentioned in the docs.
page params
JQM router plugin
Commonly, there 2 method for transfer parameter between jQuery Mobile page.
Modify Ajax address at first page, and parse the ajax to get parameter in next page.
Using HTML5 sessionStorage, a kind of WebStorage, to transfer parameter.
This is the method use ajax address to transfer parameter.
How to pass and get Parameters between two Pages in Jquery Mobile?
Using sessionStorage/localStorage to transfer parameter, you can add this code at first page,
<a href="#page_Parameter1" onclick="sessionStorage.ParameterID=123">
Before go to next page, parameter id is storaged into sessionStorage.
</a>
In next page, you can use this method to take parameter content,
$('#page_Parameter1').live('pageshow', function(event, ui) {
alert('Parameter ID: ' + sessionStorage.ParameterID);
});

How can i return a form using ajax into a view ASP.Net MVC

i just started building a small test app to help me learn MVC. i have a view that displays user comments. Under each comment i would like to have a reply action link. Clicking on the link should return a small form for adding a comment directly above the reply link.
What is the general approach for this? I'm imaging the form would be a partial view that i can somehow return using the reply link. Thanks for any help!
Using jQuery to retrieve and post the forms in partial views is how I would do it.
Just return partial view to be loaded by jQuery load:
$('#comment').load('/MyController/ActionReturnsPartial');
You should not have to retrieve anything from the server if the user is not providing any extra information along with the retrieval.
Instead of retrieving the form when the user clicks, just let the page render a form below each comment. Put the form in a div with style="display: none;". Then, when the user cliks the link, use jQuery to show the form. Something like
$('.commentlink').click(function(){
$(this).closest('div').find('.formdiv').show();
});
You may also be able to use jQuery's .toggle() method.

MVC - How to structure views for a search form with results on same page

I have MVC 1.0 app on VS2008.
I have webpage that has a search form fields and then when search button clicked uses
Ajax.BeginForm to load results in a div. Works great!
But the results have a pager that just uses an anchor with href passing in page index to controller action.
Of course the same action that is used when the search button is clicked.
So what happens is the results are displayed in new page by themselves. Because the links
are not called using Ajax.
So how can I structure my views and actions so that when a link is clicked in the pager
that the form is submitted to the action as well as the page index for the results??
Do you understand me??
Malcolm
I think I understand what you are saying.
Currently, you're using Ajax to dynamically update your results to a div. Kewl.
The trick here is to make sure each 'page' in the pager has a similar javascript function defined on the onclick event. This way, the pager doesn't do a 'postback' to the server, but the javascript method is ran ... which calls some ajax.
here's some sample html...
<a href="#" onclick="DoPagedSearch(1)>1</a> |
<a href="#" onclick="DoPagedSearch(2)>2</a> .. etc
does this make sence? make sure the pager is NOT inside a form AND notice the '#' characters? that makes sure that when u click on the text, it doesn't try and goto another HTML page, elsewhere.
Do you know how to wire up any javascript to an html element? How do u create the html code for the pager?
try that and keep us posted.
Use jquery to have the page anchors make an ajax call to the controller. Return the results as JSON or xhtml or whatever format makes you feel happy and use that to replace the content of the div, or build up and replace the contents if JSON.
If you haven't dug into jquery, I highly recommend it. The documentation is rather excellent. Let me provide you a few useful links for this:
JSON.net serializer
jQuery Documentation
fair example of using jquery for paging
The example uses an rss feed (xml) as the source, but It should get you going.

Resources