Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript work before submitting ASP.NET MVC form

I have an ASP.NET MVC view with a Beginform, that specifies an action and controller to hit on submit. But on submit I want to call a service using jQuery to get some data and then submit those data with the form.

Currently I have a submit button on the form where the onclick event of the button calls the JavaScript method. Depending of what result I get from the method I want the form to be submitted to the specified action.

Now I can't get this to work. Is it the right way to do this or should I instead make a post using jQuery? I think it would be nice to use what I have already specified as action/controller in the form.

like image 220
Rasmus Christensen Avatar asked Oct 13 '10 21:10

Rasmus Christensen


People also ask

Can you use JavaScript in ASP NET MVC?

JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.

What happens when a form is submitted in JavaScript?

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript. The method form.

Does one submit a form using JavaScript?

The method form. submit() is used for dynamic creation and sending the details to the server. The JavaScript form submission can be used for object creation and various attributes can also be used. The attributes can be class, id, tag, etc.

How can add JavaScript in ASP NET MVC?

Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.


1 Answers

I think the best way is to use event 'submit' on form, because users can want to submit form by pressing Enter in some fields. Guess, it is possible to change some input values during this event,

jQuery('form#myform').submit(function(e){
   //....
   if (somevar == false)
   {
      // stop submitting form
      e.preventDefault();
   }
   else
   {
      jQuery('input#hiddeninput').val('somevalue');
   }
})
like image 94
Aliaksei Shytkin Avatar answered Sep 21 '22 18:09

Aliaksei Shytkin