Validating that a form input is not empty - asp.net

I have this code for Form Submit..
<input type="submit" runat="server" id="buttonSubmit" value="Add" style="width:100px;" />
My BeginForm is like this..
<% using (Html.BeginForm("Insert", "StudentController", FormMethod.Post, new { #id = "exc-" }))
{%>
I have one textbox in my view I need to check my textbox is empty or not if it is Empty display alert box saying please Enter some value in textbox
other wise go to controler..
Please any body help me out?
thanks

You can do this many ways, but possibly the cleanest is to use Data Annotations on your ViewModel. For example -
public class MyViewModel
{
[Required]
public string MyProperty { get; set; }
}
Now in your View use
<% Html.EnableClientValidation(); %>
just before you start the form. This will cause a JavaScript object to be emitted in the markup sent to the client. The script looks like this example
<script type="text/javascript">
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"FirstName","ReplaceValidationMessageContents":true,"ValidationMessageId":"FirstName_validationMessage","ValidationRules":[{"ErrorMessage":"The First Name field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"LastName","ReplaceValidationMessageContents":false,"ValidationMessageId":"LastName_validationMessage","ValidationRules":[{"ErrorMessage":"The Last Name field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"EmailAddress","ReplaceValidationMessageContents":false,"ValidationMessageId":"EmailAddress_validationMessage","ValidationRules":[{"ErrorMessage":"The Email Address field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"ZipCode","ReplaceValidationMessageContents":false,"ValidationMessageId":"ZipCode_validationMessage","ValidationRules":[{"ErrorMessage":"Zip Code must be 5 character long.","ValidationParameters":{"minimumLength":0,"maximumLength":5},"ValidationType":"stringLength"},{"ErrorMessage":"Zip Code must be five digits.","ValidationParameters":{"pattern":"\\d{5}"},"ValidationType":"regularExpression"},{"ErrorMessage":"The Zip Code field is required.","ValidationParameters":{},"ValidationType":"required"}]}],"FormId":"form0","ReplaceValidationSummary":false,"ValidationSummaryId":"valSumId"});
//]]>
</script>
This object contains validation metadata that can be used by a client side validation plugin to hook up validation on the client side. The plugin that comes with ASP.NET MVC 2 is the Microsoft AJAX validator and you will need to include these scripts in the page to use the validation (MicrosoftAjax.js, MicrosoftMVCAjax.js and MicrosoftMvcValidation.js in that order).
Alternatively, if you're more comfortable with jQuery, you can get a script in the MvcFutures source that hooks the validation into the jQuery validate plugin (this isn't a fully fledged script and is missing a few pieces, such as getting client side validation summaries). The script is MicrosoftMvcJQueryValidation.js and you can get it here
The advantage of using Data Annotations is that you get the server side validation too and your client and server side validation will validate for the expected values. Also, the Data Annotations allow you to set Error Messages and names for the field labels from the attributes (error messages and display names* can also come from resource files)
*Because MVC2 was compiled against .NET 3.5 version of Data Annotations, display name cannot be set from resource files. There is a workaround to this - DisplayName attribute from Resources?.
NOW THE EASY WAY
Just set up a submit event handler on the form
var form = document.getElementById('exc-');
var oldSubmit = form.onsubmit || function() {};
form.onsubmit = function() {
var input = document.getElementById('myinput');
if (input.value === '') {
alert('please Enter some value in textbox');
return false;
}
oldSubmit();
}
or with jQuery
$('#exc-').submit(function() {
if ($('#myinput').val() === '') {
alert('please Enter some value in textbox');
return false;
}
});

Related

Multiple validation on textbox in Gridview

I have a ASP.Net gridview and in itemTemplete I have textbox for input purpose. The problem is some textbox is for numeric input and other for Character and some accept Mobile no and 1 row is for IP address.
Now i want to validate rows as per Row in gridview?
is it possible if possible then how ?
here im giving an example.Not an exact answer.So try to understand the logic.Here im giving how to validate phno and only alphabets in name.remaining you can get, like the same way.
Because of dynamic generation of textboxes we cant create validations on it.So i use "javascript"
First you need to click "View Page source"(Right click on browser page).In that we can see the "Id"s of dynamically generated textboxes.here i take two textboxes for phno and name in gridview.i get their ids by seeing their html.(Right click on browser->view page source).i get their ids like "GridView1_TextBox1_0" for name"GridView1_TextBox1_1" for phone.By using ids i create validation using Javascript.Write the below code in Head Section of Page.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
function validate() {
var phno = document.getElementById("GridView1_TextBox1_1").value;
var namechar = document.getElementById("GridView1_TextBox1_0").value;
var phoneno = /^\d{10}$/;
var name = /^[a-zA-Z]+$/;
if (!namechar.match(name)) {
alert("please enter alphabets only");
return false;
}
if(!phno.match(phoneno))
{
alert("please enter valid phno");
return false;
}
}
</script>
In this way i validate textboxes which are generated dynamically.once again its not exact answer.its a logic by using javascript.
Limitation:
Hence Javascript is client side technology.if user disable the javascript.it not works.

How to check the Condition here

<script type="text/javascript">
$('#TextEdit').click(function () {
$('#ObnAdd').val('Save');
});
</script>
<% using (Html.BeginForm("Create", "ObnTextComponents",FormMethod.Post,new {#id = "TheForm"}))
{%>
I need to check the condition if my ObnAdd Button text is Add need to go Create ActionResult
if Button text is Save I need to go Save ActionResult..
how to check this Condition in BeginForm?
thanks
From your comments it seems that it's better to check for the value of the button on the Controller side. Because you can't change your aspx code after the page loads.
So, in your controller you should have something like this (make sure your ObnAdd has name=ObnAdd):
public ActionResult SaveCreate(FormCollection form, string ObnAdd)
{
if (ObnAdd == "Save")
{
//Do save
}
else if (ObnAdd == "Create")
{
//Do create
}
//here return RedirectToAction or whatever
return RedirectToAction("Index");
}
And your HTML:
<% using (Html.BeginForm("SaveCreate", "ObnTextComponents",FormMethod.Post,new {#id = "TheForm"}))
{%>
The ASP executes server-side before pageload and has no access to the dom. Whereas the javascript executes client-side during and after pageload.
Since changing the button text is done in javascript (after all the asp runs), the button will always have the same value during pageload, so the branch is unnecessary. Also note that the asp can't access the dom of the page it's creating to test for such things. You would need to either include a library that forms the dom tree for you or use standard text operators to check the value you're looking for (like a regex).
A simple solution to what I think you're doing here would be to maintain a hidden input on the form that is also updated when you update the button. Then you can have the button submit and the page handling the form can make the necessary decisions with all information available.

ASP.NET MVC Submitting Form Using ActionLink

I am trying to use link to submit a form using the following code:
function deleteItem(formId) {
// submit the form
$("#" + formId).submit();
}
Basically I have a grid and it displays a number of items. Each row has a delete button which deletes the item. I then fire the following function to remove the item from the grid.
function onItemDeleted(name) {
$("#" + name).remove();
}
It works fine when I use a submit button but when I use action link the JavaScript from the controller action is returned as string and not executed.
public JavaScriptResult DeleteItem(string name)
{
var isAjaxRequest = Request.IsAjaxRequest();
_stockService.Delete(name);
var script = String.Format("onItemDeleted('{0}')", name);
return JavaScript(script);
}
And here is the HTML code:
<td>
<% using (Ajax.BeginForm("DeleteItem",null, new AjaxOptions() { LoadingElementId = "divLoading", UpdateTargetId = "divDisplay" },new { id="form_"+stock.Name }))
{ %>
<%=Html.Hidden("name", stock.Name)%>
<a id="link_delete" href="#" onclick="deleteItem('form_ABC')">Delete</a>
<% } %>
</td>
My theory is that submit button does alter the response while the action link simply returns whatever is returned from the controller's action. This means when using submit the JavaScript is added to the response and then executed while in case of action link it is simply returned as string.
If that is the case how can someone use action links instead of submit buttons.
UPDATE:
Seems like I need to perform something extra to make the action link to work since it does not fire the onsubmit event.
http://www.devproconnections.com/article/aspnet22/posting-forms-the-ajax-way-in-asp-net-mvc.aspx
My guess is the MS Ajax form knows how to handle a JavaScriptResponse and execute the code whereas your plain old Action link, with no relationship to the AjaxForm, does not. I'm pretty sure the MS ajax library essentially eval()s the response when it sees the content type of javascript being sent back.
Since you have no callback in your deleteItem() method there is no place for the script to go. To fix you'll have to manually eval() the string sent back which is considered a bad practice.
Now I'm not familiar with the MS Ajax library to be certain of any of this but what your doing is possible. I'd do things differently but don't want to answer with a "my way is better" approach ( especially because your blog has helped me before ) but I'd like to show this can be easier.
I'd ditch the form entirely and use unobtrusive javascript to get the behavior you want. IN psuedo jqueryish ( don't know ms ajax ) code:
function bindMyGrid() {
$('.myDeleteLink').onclicksyntax( function() {
//find the td in the row which contains the name and get the text
var nameTdCell = this.findThisCellSibling();
//do an ajax request to your controller
ajax('myUrl/' + nameTdCell.text(), function onSuccessCallback() {
//get the tr row of the name cell and remove it
nameTdCell.parent().remove();
});
});
}
This also gains the benefit of not returning javascript from your controller which some consider breaking the MVC pattern and seperation of concerns. Hope my psuedo code helps.
Try without the UpdateTargetId property in the AjaxOptions (don't specify it)
new AjaxOptions() { LoadingElementId = "divLoading" }
What about just change look of a standard or using some css class? It'll look like a link and you'll avoid some problems you get with anchors - user will be able to click on it by a mouse wheel and open that link in a new tab/window.

C# .NET and Javascript Confirm

I have a C# ASP.NET web page with an xml file upload form. When the user clicks 'upload', a javascript confirm alert will pop up asking the user, "is this file correct?". The confirm alert will only activate if the file name does not contain a value from one of the other form fields.
What is the best way to combine the use of a C# ASP.NET form and a javascript confirm alert that is activated if the name of a file being uploaded does not meet certain criteria?
There's not much you need to do with C# for this page, it sounds like most of this will be done on the client side.
Add the fileupload control and a button to your .aspx form. Set the Button's OnClientClick property to something like
OnClientClick = "return myFunction()"
and then write a javascript function like:
function myFunction()
{
// Check other text values here
if (needToConfirm){
return confirm('Are you sure you want to upload?');
}
else return true;
}
Make sure "myFunction()" returns false if you wish to cancel the postback (i.e. the user clicked "no" in the confirm dialog). This will cancel the postback if they click "No".
I suppose you are putting value of valid string in a hidden field (you haven't mentioned). Implement OnClientClick for Upload button:
<asp:button .... OnClientClick="return confirmFileName();"/>
<script type="text/javascript">
function confirmFileName()
{
var f = $("#<%= file1.ClientID %>").val();
var s=$("#<%= hidden1.ClientID %>").attr("value");
if (f.indexOf(s) == -1) {
if (!confirm("Is this correct file?")) {
$("#<%=file1.ClientID %>").focus();
return false;
}
}
return true;
}
</script>
EDIT:- Regarding <%= file1.ClientID %>.
This will be replaced by the client side ID of the file upload control like ctl00$ctl00$cphContentPanel$file1. It puts the script on steroids with respect to using something like $("input[id$='file1']"). For more information please see Dave Wards' post.
window.onload = function() {
document.forms[0].onsubmit = function() {
var el = document.getElementById("FileUpload1");
var fileName = el.value;
if(fileName.indexOf("WHATEVER_VALUE") == -1) {
if(!confirm("Is the file correct?")) {
el.focus();
return false;
}
}
return true;
}
}
I had problems implementing this kind of thing to work in both IE and FireFox because of the way events work in those browsers. When I got it to work in one of them, the other would still cause a postback even if I cancelled out.
Here's what we have in our code (the browser test was stolen from elsewhere).
if (!window.confirm("Are you sure?"))
{
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
window.event.returnValue = false;
else
e.preventDefault();
}
In addition to using client side validation, you should also add a CustomValidator to provide validation on the server side. You cannot trust that the user has Javascript turned on, or that the user has not bypassed your Javascript checks.

Retrieving data from Html.DropDownList() in controller (ASP MVC) | string returned?

I have the following problem:
I have a form in site/banen (currently local running webserver) which is using a SQL database. The link is made using ADO.net and is instantiated in the controller in the following way:
DBModelEntities _entities;
_entities = new DBModelEntities(); // this part is in the constructor of the controller.
Next, I use this database to fill a Html.DropDownList() in my view. This is done in two steps. At the controller side we have in the constructor:
ViewData["EducationLevels"] = this.GetAllEducationLevels();
and a helper method:
public SelectList GetAllEducationLevels()
{
List<EducationLevels> lstEducationLevels = _entities.EducationLevels.ToList();
SelectList slist = new SelectList(lstEducationLevels, "ID", "Name");
return slist;
}
In the view I have the following:
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<!-- various textfields here -->
<p>
<label for="EducationLevels">EducationLevels:</label>
<!-- <%= Html.DropDownList("EducationLevels", ViewData["EducationLevels"] as SelectList)%> -->
<%= Html.DropDownList("EducationLevels", "..select option..")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
Now, the form is rendered correctly when I browse to the create page. I can select etc. But when selected I have to use that value to save in my new model to upload to the database. This is where it goes wrong. I have the following code to do this in my controller:
//
// POST: /Banen/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection form)
{
// set rest of information which has to be set automatically
var vacatureToAdd = new Vacatures();
//vacatureToAdd.EducationLevels = form["EducationLevels"];
// Deserialize (Include white list!)
TryUpdateModel(vacatureToAdd);
// Validate
if (String.IsNullOrEmpty(vacatureToAdd.Title))
ModelState.AddModelError("Title", "Title is required!");
if (String.IsNullOrEmpty(vacatureToAdd.Content))
ModelState.AddModelError("Content", "Content is required!");
// Update the variables not set in the form
vacatureToAdd.CreatedAt = DateTime.Now; // Just created.
vacatureToAdd.UpdatedAt = DateTime.Now; // Just created, so also modified now.
vacatureToAdd.ViewCount = 0; // We have just created it, so no views
vacatureToAdd.ID = GetGuid(); // Generate uniqueidentifier
try
{
// TODO: Add insert logic here
_entities.AddToVacatures(vacatureToAdd);
_entities.SaveChanges();
// Return to listing page if succesful
return RedirectToAction("Index");
}
catch (Exception e)
{
return View();
}
}
#endregion
It gives the error:
alt text http://www.bastijn.nl/zooi/error_dropdown.png
I have found various topics on this but all say you can retrieve by just using:
vacatureToAdd.EducationLevels = form["EducationLevels"];
Though this returns a string for me. Since I'm new to ASP.net I think I am forgetting to tell to select the object to return and not a string. Maybe this is the selectedValue in the part where I make my SelectList but I can't figure out how to set this correctly. Of course I can also be complete on a sidetrack.
Sidenote: currently I'm thinking about having a seperate model like here.
Any help is appreciated.
You can't return an object from usual <SELECT> tag wich is rendered by Html.DropDownList() method, but only string variable could be returned. In your case ID of EducationLevels object will be send to the server. You should define and use one more custom helper method to reconstruct this object by ID.

Resources