How do I post back to an MVC controller action via Javascript - asp.net

Currently I have a aspx page that is defined as:
<%Using Html.BeginForm("SaveNotifications", "Notifications", FormMethod.Post, New With {.id = "NotificationForm"})%>
...
<tr>
<td colspan="3">
<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" />
</td>
</tr>
</table>
</fieldset>
<%End Using %>
I want to change this so that my input button fires a javascript function so that I can do some complex validation of the form and THEN post to the controller.
I changed my submit button to:
<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" onclick="onSave(); return false;" />
The onSave() method would fire but not post back to the controller.
The controller is defined as:
<HttpPost()> _
<MultiButton(MatchFormKey:="SaveNotifications", MatchFormValue:="Save")> _
Function SaveNotifications(ByVal NotificationForm As FormCollection) As ActionResult
...
End Function
How do I change this so that the javascript fires, runs my validation and then hits this controller action?
Thanks

Change your submit button to
<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" onclick="return onSave();" />
Then in the javascript onSave() function, return true or false depending on the validation.
function onSave()
{
var isValid = true;
// ... do your validation ...
// ie:
// if (field1.value.length == 0)
// isValid = false;
// returning true will post the form. False will halt it.
return isValid;
}

Related

How to get checkbox values from another form with asp .net MVC4?

Here is a simplified example. My first form :
#using (Html.BeginForm("Action1", "MyController", FormMethod.Post))
{
<input id="cb" type="checkbox" value="true" name="MyCheckBox" />
<label for="cb">Check this out</label>
}
And late in the same view, another form :
#using (Html.BeginForm("Action2", "MyController", FormMethod.Post))
{
<input type="submit" value="Submit" id="submit" />
}
How to efficiently get the value (checked or not) of this checkbox, in the action Action2 in MyController ?
Browser don't send values from another form in requests.
The only way to do it is to handle onsubmit event with js/jquery, add value to form and submit it with js.

Conditionally disable validation

I have form with few text boxes which goes through validation (both server and client sides). In the form I have buttons: "Next", "Back", "CanceL". So I don't need validation to fireup then user clicks "back" or "cancel" buttons. How can I achieve this?
Thanks in advance!
Some sample:
<div class="buttons">
<input type="submit" name="cancelButton" value="" />
<input type="submit" name="backButton" value="" />
<input type="submit" name="nextButton" value="" />
</div>
<% using (Html.BeginForm()) { %>
<p>
<table style="width: 200px">
<tr><td align="center" colspan=2><%= Html.ValidationMessageFor(m => m.street) %><%= Html.DropDownListFor(m => m.street, Model.streetsList) %></td></tr>
<tr><td colspan=2> </td></tr>
<tr><td valign="bottom" align="right" style="width: 75px"><%= Html.LabelFor(m => m.flatNumber) %>:</td><td align=left><%= Html.TextBoxFor(m => m.flatNumber, new { maxlength = 6, style = "width: 48px;" })%> <%= Html.ValidationMessageFor(m => m.flatNumber) %></td></tr>
</table>
<br />
<input type="submit" class="refusal button red floatL" name="cancelButton" value="" />
<input type="submit" class="back button green floatL" name="backButton" value="" />
<input type="submit" class="continue button green floatR marR" name="nextButton" value="" />
</div>
<div class="clear">
</div>
<% } %>
At the server side I use DataAnnotations attributes for validation.
the Button class has a CausesValidation property - if that is set to false, validation won't be triggered on postback.
Example:
<asp:Button id="btnCancel" CausesValidation="false" onClick="bntCancel_Click" Text="Cancel" runat="server" />
Note that this will disable the ASP.NET validators - if you have your own validation you will need to disable it another way.
Surround the text boxes with a form and turn next, back, and cancel into submit buttons. On event onsubmit, assign a method which returns true if the form is valid and should proceed to send it to the server, otherwise false.
So I would expect something along the lines of:
<form id="navigatorForm">
<!-- Various text forms here -->
<input type="submit" value="Back" onsubmit="back()" />
<input type="submit" value="Next" onsubmit="next()" />
<input type="submit" value="Cancel" onsubmit="cancel()" />
<input type="hidden" id="operation" name="operation" value="" />
</form>
<script type="text/javascript">
function validate() {
// Perform validation here
// If okay, return true, else false
}
function next() {
document.getElementById('operation').value = 'next';
if(!validate()) {
alert('Form is not filed correctly. Please pay more attention!');
return false; // Do not send to server!
} else {
return true;
}
}
function back() {
document.getElementById('operation').value = 'back';
return true;
}
function cancel() {
document.getElementById('operation').value = 'cancel';
return true;
}
</script>
Notice that unlike next(), back() and cancel() unconditionally return true, meaning that the request is sent to the server in any circumstance. At this point, on the server side, you'd need only to check to see if operation is next to know whether or not you should perform further testing.

Submit form when Enter is pressed

I have an aspx page with many buttons and i have a search button whose event i want to be triggered when user press enter.
How can i do this?
You set the forms default button:
<form id="Form1"
defaultbutton="SubmitButton"
runat="server">
Make it the default button of the form or panel.
Either one has a DefaultButton property that you can set to the wanted button.
$(document).ready(function() {
$("#yourtextbox").keypress(function(e) {
setEnterValue(e);
});
});
function setEnterValue( e) {
var key = checkBrowser(e);
if (key == 13) {
//call your post method
}
function checkBrowser(e) {
if (window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return key;}
call the above function and it will help you in detecting the enter key and
than call your post method.
The best way to make from make actions using enter button and on click of the button without the headache to write js check for each input you have if the user press enter or not is using submit input type.
But you would face the problem that onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});

how can we cal two servlets from the same html page?

I need to design a page to register as well as login a user.By clicking login button login servlet should be called.And on clicking register button,register servlet will be called.how can i do this?
Having two forms that post to different places is the simplest method
Name your buttons:
<input type="submit" name="form_action" value="Login" />
and
<input type="submit" name="form_action" value="Register" />
When it comes to processing the form, just hookout form_action and it should equal Login or Register.
This requires some more server-side logic but should work if you need your two forms to be tightly combined.
You can include some Javascript code for this.
<form name="Form1" method="post">
Your Name <input type="text" name="text1" size="10" /><br />
<INPUT type="button" value="ButtonLogin" name=button1 onclick="return OnButtonLogin();">
<INPUT type="button" value="ButtonRegister" name=button2 onclick="return OnButtonRegister();">
</form>
like this:
<script language="Javascript">
<!--
function OnButtonLogin()
{
document.Form1.action = "Login.do"
document.Form1.target = "_blank";
document.Form1.submit();
return true;
}
function OnButtonRegister()
{
document.Form1.action = "Register.do"
document.Form1.target = "_blank";
document.Form1.submit();
return true;
}
-->
</script>

ASP.NET MVC url search parameter without question mark

I have a route defined as:
routes.MapRoute("AllUsers",
"Users/Search/{Search}", new {
Controller = "Users", action=
"Index"});
and the form as:
<% using (Html.BeginForm("Index", "Users/Search/", new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
<input id="searchBox" name="search" type="text" />
<input type="submit" id="submit" value="Search" /><%} %>
Currently as expected this creates a url of
../Users/Search/?search=searchTerm
but what I would like is:
../Users/Search/searchTerm
How is this possible? I thought of using javascript, but this seems a little dirty. Is there a more streamlined way of accomplishing this?
You cannot do that with an HTML form. Though you can mimic the behavior with JavaScript.
How about a server-side redirect?
You could do:
<input type="submit" id="submit" value="Search"
onclick="$('form').attr('action', $('form').attr('action') + $('#searchBox').val());" />
Which seems a little ugly. You could also not use a form and have this:
<input type="button" id="submit" value="Search"
onclick="window.location.href = 'search/' + $('#searchBox').val();" />
Outside of this, you could allow the original submit to go to the weird url, but use RedirectToAction in your controller.
Using jQuery you could something like this:
<script type="text/javascript">
$(function(){
$("#submit").click(function(){
document.location.href = $("form").attr("action") + $("#searchBox").val();
return false;
});
});
</script>
Try to change like this:
routes.MapRoute("AllUsers",
"Users/Search/{id}", new { Controller = "Users", action= "Index"});
and the form as:
<% using (Html.BeginForm("Index", "Users/Search/",
new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
<input id="searchBox" name="id" type="text" />
<input type="submit" id="submit" value="Search" /><%} %>
Not tested, but "id" is default route value which are not creating "?name=value".

Resources