Form validation for saving before exit - asp.net

I created a form in asp.net and now I need to add a validation to it, so if any of the fields has been populated and user will try to leave the page, the pop-up will appear asking "Do you want to exit without saving?". Is there a simple way I can to this?
<% using (Html.BeginForm("Create", "Damages", FormMethod.Post))
{%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%=Html.LabelFor(model => model.OrderId)%>
</div>
<div class="editor-field">
<%= Model.OrderId%>
</div>
....
<%=Html.HiddenFor(model => model.Id)%>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>

You can use the onbeforeunload event:
<script>
window.onbeforeunload = function() {
if( isDirty ) {
return 'Do you want to exit without saving?';
}
}
</script>
Of course you need to keep track of form field changes and set the isDirty flag accordingly.
https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
http://msdn.microsoft.com/en-us/library/ie/ms536907%28v=vs.85%29.aspx

Related

Rails 4 button_to using helper improper redirection

I am building an index for one of my models. Instead of the usual table, I want to have two combo-boxes: one for selecting the object, the other for selecting the method (either edit or destroy). Upon clicking the submit button, I should be redirected to the appropriate method reference (e.g. admin_users/1/edit or admin_users/17/destroy). I have written a helper that constructs the url reference, but for some reason it does not work. when I use button_to I get redirected to the create method, when I use button_tag nothing works. Any ideas?
view code:
<%= form_tag do %>
<p id="notice"><%= flash[:notice] %></p>
<h1>Listing admin_users</h1>
<p><strong>select admin user</strong></p>
<%= select_tag(#req_id, options_from_collection_for_select(#admin_users, :id, :login)) %>
<br/>
<p><strong>select action</strong></p>
<%= select_tag(#oper, options_for_select([['edit'],['destroy']])) %>
<br/>
<%=button_tag 'go go!', get_path(#req_id,#oper) %>
<% end %>
helper code:
module AdminUsersHelper
def get_path(req_id,oper)
a=[req_id, oper].join("/")
["admin_users", a].join("/")
end
end
The default method for a form submit is POST. You'll need to change the method accordingly.
<%= form_tag( '/users/confirm', method: :get ) %>
May I suggest submitting with Javascript? You'll have a more dynamic control over the method of the submission. Take a look Here
so, eventually I went on the javascript solution, just as #Hassanin Ahmed suggested. Thanks for Helping!
<%= form_tag('/admin_users', id: "admin_users_menu") do %>
[...]
<font size=4>
<u>select user:</u>
</font>
<br>
<br>
<select id="admin_user_id" name="admin_user[id]">
<%= options_for_select #admin_users.collect{|user| [user.login, user.id]} %>
</select>
<br>
<br>
<font size=4> <u>select option:</u></font><br><br>
<input type="radio" checked name="select_op" value= "edit" > edit
<br>
<br>
<input type="radio" name="select_op" value= "delete" > delete
<br>
<br>
<%= submit_tag "go" %>
<br>
<br>
<% end %>
<script>
$(function (){
$("#admin_users_menu").submit(function() {return direct_me() })
})
function direct_me(){
//getting the admin_user id
var au_id=$('select').val()
//getting the desired method
var op=$('input[name=select_op]:radio:checked').val()
//making the default url
var u="admin_users/"+au_id
var f=$("form")
if(op=='edit'){
u=u+"/edit"
f.attr("method","GET")
}
else if(op=='delete'){
f.attr("method","POST")
f.append("<input type='hidden' name='_method' value='delete'>");
}
f.attr("action",u)
if(op=='delete') return confirm("Are you sure?")
}
</script>

How do I conditionally render a form in Razor?

When I use the following code, I get a friendly error message (as friendly as YSCD's get) telling me I shouldn't use '#', yet when I don't use it, my form declaration renders as literal Razor code, not as the intended HTML elements. What am I doing wrong?
#if (Model.Step == Trocrates.Web.Models.PasswordResetModel.PasswordResetSteps.StartRequest)
{
#using (Html.BeginForm()) { Html.ValidationSummary(true);
<fieldset style="border: 0px;">
<div class="editor-label">
#Html.LabelFor(model => model.UserName);
</div>
<div class="editor-field">
Html.EditorFor(model => model.UserName) Html.ValidationMessageFor(model => model.UserName)'
<input type="submit" value="Log In" />
#Html.ActionLink("Send", "BeginResetPassword", "Account")
</div>
</fieldset>
}
}
Sorry readers, it was originally that less visible open brace glyph on the same line as BeginForm that caused confusion. When I close that things fell back into place.
Did you try removing the # symbol on the using statement? Since you're already in code mode because of the if block the # symbol doesn't mean anything there. That's the only thing off hand that looks out of place to me.

JQuery Validate Plugin MS MVC: Won't validate

I'm trying out the jQuery Validation plugin
jQuery Docs
Here is the markup of my form:
<% using (Html.BeginForm("action", "contoller", null, FormMethod.Post, new { id = "sxform" })){%>
<div id="manifest">
Manifest Option:<br />
<%= Html.DropDownList("docid", ViewData["manifests"] as SelectList, new { #class = "required" })%>
</div>
<div id="release">
Release Version:<br />
<%= Html.TextBox("release", null, new { #class = "required" })%>
</div>
<div id="locale">
Localization:<br />
<%= Html.DropDownList("localization", ViewData["localizations"] as SelectList, new { #class = "required" })%>
</div>
<div id="label">
Label:<br />
<%= Html.TextBox("label", null, new { #class = "required" })%>
</div>
<div id="session">
Session ID (optional):<br />
<%= Html.TextBox("sessionInput", null, new { #class = "required" })%>
</div>
<div id="submit"><input type="submit" value="Build" /></div>
<% } %>
JS:
$(document).ready(function(){
$("#sxform").validate();
});
I am using MS MVC HTML Helpers to render this form. The resulting markup looks fine. IE each input and selection element contains the attribute 'class' with the value 'required'.
When I submit this form the validation does noting. Can someone familiar with this library help? It looks pretty widely used.
Thanks!
You code looks fine and should work. Make sure you have included the plugin:
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
Also look for possible javascript errors in the FireBug console.

Passing the value of a Textboxfor into ActionLink

Having a little trouble and wondered if anyone could help :-)
I am trying to pass the value that a user enters into a html.Textboxfor to an html.Action link.
As shown below :
<%=Html.TextBoxFor(m => m.OrderQty)%>
<p class="button" >
<%: Html.ActionLink("Add to cart",
"AddToCart",
"ShoppingCart",
new { id = Model.Product.ProductId, Qty = Model.OrderQty }, "")%>
</p>
But when i put a breakpoint in the AddToCart Qty is always 0 :-(
Does anyone have any ideas ?
Thanks
John
I would recommend you using a form instead of an action link. This way the value entered in the textbox will be automatically sent to the server and you don't have to worry about javascript:
<% using (Html.BeginForm("AddToCart", "ShoppingCart",
new { id = Model.Product.ProductId, Qty = Model.OrderQty },
FormMethod.Get)) { %>
<%= Html.TextBoxFor(m => m.OrderQty) %>
<input type="submit" value="Add to cart" />
<% } %>

Cannot call other action

I'm studying ASP MVC, and developping SportsStore (Create/Edit feature). When Create a product, Create action will view a Edit view, but when press Sudmit, it call action Create (Post), althrough I will set it call Edit action:
<% using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype="multipart/form-data" }))
{%>
<%--<%= Html.ValidationSummary() %>--%>
<%--<%= Html.Hidden("ProductID") %>--%>
<p>Name: <%= Html.TextBox("Name")%>
<div><%= Html.ValidationMessage("Name")%></div>
</p>
<p>Description: <%= Html.TextArea("Description", null, 4, 20, null)%>
<div><%= Html.ValidationMessage("Description")%></div>
</p>
<p>Price: <%= Html.TextBox("Price")%>
<div><%= Html.ValidationMessage("Price")%></div>
</p>
<p>Category: <%= Html.TextBox("Category")%>
<div><%= Html.ValidationMessage("Category")%></div>
</p>
<p>
Image:
<% if (Model.ImageData == null)
{ %>
None
<% }
else
{ %>
<img src= "<%= Url.Action("GetImage", "Products", new {Model.ProductID}) %>" />
<% } %>
<div>Upload new image: <input type="file" name="file" id="file" /></div>
</p>
<input type="submit" value="Save" />
<%= Html.ActionLink("Cancel and return to list", "Index")%>
<% } %>
Please help me fix it
The code you have seems reasonable if you want it to post back to the Edit action. Your question is a bit confusing, but I'm going to assume that you want to reuse the view and have it post back to Create when rendered from Create and Edit when rendered from Edit. The easiest way is to simply omit the parameters from the BeginForm call. This will cause the form action to be set to the current controller and action, which would give you what you seem to want. An alternative would be to develop templates (display/editor) for the model but have separate views for Create/Edit that simply render the template Html.EditorFor( m => m, "ProductTemplate" ). This would allow you to customize the view -- perhaps the Create view requires you to upload an image? -- yet still reuse most of the code.

Resources