follow me
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Submit a form using asp.net MVC

Ok well..there a lot of ways on how to submit your forms depending on your needs.
I'm gonna show few of those..and its up to you what you gonna used.

The normal way of submitting forms.

Views File (Register.aspx)


<% using (Html.BeginForm()) { %>


Account Information



<%= Html.TextBox("username") %>


// more code in here



<% } %>


Controller File (Home.cs)


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string username,...)
{

if (string.IsNullOrEmpty(username))
{
return View();
}
// more code in here for checking
}


Submit a form using Javascript


<% using (Html.BeginForm(null, null, FormMethod.Post, new { id="myForm"}))
{ %>
//code here
<% } %>

and then:

 $("#myForm").submit(); 


and do not forget to include jquery-1.2.6.js that comes with mvc (or use a higher version).
The Home.cs file is same as the above code.

If you want to do a client side checking before submitting your data on the server..you have to do the more complex way.

   
<% using (Html.BeginForm("Register", "Home", FormMethod.Post, new { id="myForm", onsubmit="return !stopThis();", enctype="multipart/form-data" }))
{%>
//code here
<% } %>

and then:
   
function stopThis() {
//Mandatory fuction where u can check all ur data if it was all correct and fill up
if (Mandatory()) {
// let say we have a notification element name notify_msg
document.getElementById('notify_msg').innerHTML = 'Pls. Fill up all the Required Fields';
return true;
}
return false; // require fields are all correct
}


Home.cs

   
public ActionResult SubmitCareerForm(FormCollection frm)
{
// no more checking on the field
// code here
}


Take a look on the Home.cs file, see the [AcceptVerbs(HttpVerbs.Post)] it was removed on the last sample. No need for that since we are already
pointing the funtion on the Home file using (Html.BeginForm("Register", "Home",.....

Theres also an elegant way to ajaxify you forms (with jquery) . Never try that one though.

ciao.

Read More...