How to add required field in MVC3 ? (Not using Model) - asp.net-mvc-3

I want to add a required field validation on textboxes, I'm not using any model parameters(Annotations) for these textboxes. How to achieve this?
Following is my code:
#using (Html.BeginForm())
{
<h1> 3D Pay Örnek Sayfa</h1>
<table class="tableClass">
<tr class="trHeader">
<td>Test</td>
<td>#Html.TextBox("TestIt")</td>
</tr>
</table>
}

Well, you really should use a model, but if you insist doing things by hand, I'd still recommend using the jquery validation plugin.
An example based on http://docs.jquery.com/Plugins/Validation#Example:
(Note: the bit you're looking for is #Html.TextBox("TestIt", "", new { #class="required" }), which add the class="required" attribute to the textbox, which in turn tells jquery validate that it's a required field.)
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
<script>
$(document).ready(function(){
$("form").validate();
});
</script>
</head>
<body>
#using (Html.BeginForm())
{
<center>
<h1> 3D Pay Örnek Sayfa</h1>
<table class="tableClass">
<tr class="trHeader">
<td>Test</td>
<td>#Html.TextBox("TestIt", "", new { #class="required" })</td>
</tr>
</table>
</center>
<input type="submit" id="SubmitData" name="SubmitData" value="Submit" />
}
</body>
</html>
Please remember this is just client side validation - you also need to validate on the server side too. As you're not using a model, this will probably mean some custom controller code to validate each input.

Even though you said you're not using a model, I would strongly recommend using a model.
Model:
public class TestModel
{
[Required]
public string TestIt {get; set;}
}
Markup:
#Html.TextBoxFor(m => m.TestIt)
#Html.ValidationMessageFor(m => m.TestIt)
See How to: Validate Model Data Using DataAnnotations Attributes for more information.
If you are dead set on not using a model, you could validate client side with jQuery Validate, but it will require more code.

Related

Handling events and accessing bound values in polymer paper-input -- is this a good pattern?

My question is whether the following is a good pattern for Polymer?
The other purpose for my posting is to show how to handle events and access bound values from Polymer elements in the mainline of your html. I couldn't find good examples and it took me some time to get my head around how this should work so hopefully it is of use to others (assuming I have it right!)
I recognize that I could encapsulate the entire handling within a new Polymer element but sometimes this seems a bit awkward.
Note if you want try this code you will need to update the references to the Polymer elements.
<!--
Use the template tag to wrap your Polymer elements with data binding: Will Hopkins
-->
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
<title>paper-input</title>
<!--
Update the following script and links to reflect your Polymer element locations
-->
<script src="/polymer/platform/platform.js"></script>
<link href="/polymer/font-roboto/roboto.html" rel="import">
<link href="/polymer/paper-input/paper-input.html" rel="import">
<link href="/polymer/paper-button/paper-button.html" rel="import">
<style shim-shadowdom>
body {
font-family: RobotoDraft, 'Helvetica Neue', Helvetica, Arial;
margin: 0;
padding: 24px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-touch-callout: none;
}
paper-input.narrow {
width: 150px;
}
</style>
</head>
<body unresolved>
<section>
<!--
OK here is the secret sauce. Wrap your Polymer tags with the template tag, give it and id and specify auto binding
-->
<template id="user-maintenance" is="auto-binding">
<div><paper-input label="ID" floatinglabel=true type=number value="{{iD}}"></paper-input></div>
<div><paper-input label="First Name" id="firstName" floatinglabel=true value="{{firstName}}"></paper-input></div>
<div><paper-input label="Last Name" floatinglabel=true value="{{lastName}}"></paper-input></div>
<div><paper-input label="Blurb" floatinglabel=true multiline maxrows=5 value="{{blurb}}"></paper-input></div>
<div><paper-input label="Concurrency Control"value="{{conControl}}" disabled></paper-input></div>
<br>
<p>id: {{iD}}, First Name: {{firstName}}, Last Name: {{lastName}}, Blurb: {{blurb}}, Concurrency Control: {{conControl}}</p>
<div>
<paper-button raised id="createButton" on-tap="{{createClicked}}">Create</paper-button>
<paper-button raised id="retrieveButton" on-tap="{{retrieveClicked}}">Retrieve</paper-button>
<paper-button raised id="updateButton" on-tap="{{updateClicked}}">Update</paper-button>
<paper-button raised id="deleteButton" on-tap="{{deleteClicked}}">Delete</paper-button>
</div>
</template>
</section>
<script>
//
// OK now lets get a handle to our template
//
var inlineBinding = document.getElementById('user-maintenance');
// now we can set an input value
inlineBinding.conControl = 13;
// and handle events
inlineBinding.createClicked = function() {
// and retrieve values
alert("Create fired for: " + inlineBinding.firstName + " " + inlineBinding.lastName);
};
inlineBinding.retrieveClicked = function() {
alert("Retrieve fired for: " + inlineBinding.firstName + " " + inlineBinding.lastName);
};
inlineBinding.updateClicked = function() {
alert("Update fired for: " + inlineBinding.firstName + " " + inlineBinding.lastName);
};
inlineBinding.deleteClicked = function() {
alert("Delete fired for: " + inlineBinding.firstName + " " + inlineBinding.lastName);
};
</script>
</body>
This is perfectly fine and something we show off in the docs: https://www.polymer-project.org/docs/polymer/databinding-advanced.html#bindingoutside
<template is="auto-binding"> is in fact a custom element :), so you shouldn't shy away from it. The only thing it doesn't do (compared to <polymer-element> is <prop>Changed() handlers).

MVC3 with Ajax partial view - OnBegin validation not performed

In an MVC3 application I have a view rendering two Ajax partial views: a Create partial view and a List one. In the Create partial view I try to fire client validation on OnBegin event, but this does not happen.
The error messages I get, when I force errors, are the one indicated in the model annotations, and not the ones I define in the validation function called OnBegin (e.g.:
leaving the event place empty, I get "The event place is required" (annotation) instead of "Where did it take place?" (FieldsValidation function),
for the event description I get "The event description is required" (annotation) instead of "Tell us sth about it!" (FieldsValidation function)
and the validation summary message sais "Error on creation. Please retry after corrections." instead of "Save failed. Please correct errors and retry."(FieldsValidation function)).
I tried to put a breakpoint in the FieldsValidation function, but it was never reached.
Just to make sure, I also tried to call OnBegin a function displaying an alert (after the test I restored the original call to FieldsValidation function):
function toDoOnBegin() { alert("This is onBegin"); }
The alert never displays!
If all fields are properly filled in, the event is correctly created and displayed in the event list (the other partial view). The problem is uniquely the function call OnBegin.
Please explain me what did I do wrong, did I miss to include something or what else is it?
Thank you truly.
Web.config
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Model:
public partial class Event
{
public int client_ID { get; set; }
[Required(ErrorMessage="The event date is required")]
[DataType(DataType.Date, ErrorMessage="The event date is invalid")]
public System.DateTime event_date { get; set; }
[Required(ErrorMessage="The event place is required")]
public string event_place{ get; set; }
[Required(ErrorMessage="The event description is required")]
public string event_description{ get; set; }
}
_Layout.cshtml :
Style sheets
<link href="#Url.Content("~/Content/styles.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/nivo-slider.css")" rel="stylesheet" type="text/css" media="screen"/>
<link href="#Url.Content("~/Content/themes/redmond/jquery-ui-1.8.18.custom.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery.timepicker.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery.alerts.css")" rel="stylesheet" type="text/css" media="screen"/>
jQueries for datetimepicker plugin needed on several other pages
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.18.custom.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.slider.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.datepicker-fr.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-timepicker-addon.js")" type="text/javascript"></script>
jQueries for other application components
<script src="#Url.Content("~/Scripts/jquery.alerts.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/OJscript.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.nivo.slider.pack.js")" type="text/javascript"></script>
jQueries for validation
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Index.cshtml
#model MyApp.ViewModels.EventViewModel
#{
ViewBag.Title = "Events";
}
<div id="divUpdateable">
#Html.Partial("_Create", Model)
</div>
<div id="divList">
#Html.Partial("_ListEvents", Model.EventsList)
</div>
_Create.cshtml
#model MyApp.ViewModels.EventViewModel
<script type="text/javascript">
function FieldsValidation() {
$("#idformCreate").validate({
errorContainer: $($('div.validation-summary-errors')),
errorLabelContainer: $("ul", $('div.validation-summary-errors')),
wrapper: 'li',
errorClass: "input-validation-error2",
rules:
{
'Event.event_date':
{
required: true
},
'Event.event_place':
{
required: true
},
'Event.event_description':
{
required: true
}
},
messages:
{
'Event.event_date':
{
required: "Date is required"
},
'Event.event_place':
{
required: "Where did it take place?"
},
'Event.event_description':
{
required: "Tell us sth about it!"
}
}
}).form();
if (!$("#idformCreate").valid()) {
$("div.validation-summary-errors span").html("Save failed. Please correct errors and retry.");
return false;
}
return true;
}
</script>
#using (Ajax.BeginForm("Create", "Event", new { clientID = Model.Event.client_ID }, new AjaxOptions
{
UpdateTargetId = "divUpdateable",
OnBegin = "FieldsValidation",
InsertionMode = InsertionMode.Replace,
OnSuccess = "getForm('" + Url.Action("ListEvents", "Event", null) + "','divList')"
}, new { id = "idformCreate" }))
{
#Html.ValidationSummary(false, "Error on creation. Please retry after corrections.")
<p>#Html.ValidationMessage("_FORM")</p>
<div class="validation-summary-errors">
<span></span>
<ul>
</ul>
</div>
<fieldset style="width: 800px; line-height: 1.4em;">
<legend>Add an event</legend>
<table style="width: 100%; padding-bottom: 0; padding-top: 0; border: 0;">
<tr>
<td style="width: 90px; border: 0;">
#Html.LabelFor(model => model.Event.event_date)
</td>
<td style="width: 200px; border: 0;">
#Html.EditorFor(model => model.Event.event_date, new { #class = "date" })
#Html.ValidationMessageFor(model => model.Event.event_date, "*")
#Html.HiddenFor(model => model.Event.client_ID)
</td>
</tr>
<tr>
<td style="width: 80px; border: 0; text-align: right;">
#Html.LabelFor(model => model.Event.event_place)
</td>
<td style="width: 120px; border: 0;">
#Html.DropDownList("Event.event_place", Model.PlacesList, "Where?", new { #style = "width: 100px;" })
#Html.ValidationMessageFor(model => model.Event.event_place, "")
</td>
</tr>
<tr>
<td style="width: 90px; border: 0;">
#Html.LabelFor(model => model.Event.event_description)
</td>
<td style="width: 600px; border: 0;" colspan="5">
#Html.TextAreaFor(model => model.Event.event_description, new { #class = "input_txt_nofloat", #style = "width:590px" })
#Html.ValidationMessageFor(model => model.Event.event_description, "*")
</td>
</tr>
<tr style="height: 64px;">
<td colspan="2" style="text-align: center;">
<br />
<br />
<input type="submit" value="Save" class="submit" style="width: 280px" />
</td>
</tr>
</table>
</fieldset>
}
Here is the answer: (with a great thanks for BrockAllen)
If you are doing your own client-side validation then you should
remove jquery.validate.unobtrusive.min.js. This is MVC's client side
validation code and they will conflict if both are using
jquery.validate.
Hopefully, this will help other people too.
On begin you are calling:
OnBegin = "FieldsValidation",
If you want your alert to be displayed, then you need:
OnBegin = "toDoOnBegin"

why do i get scroll bars when using google line chart?

I am using google line chart api and no matter how big i make the div chart dimentions, it always shows a horizontal and vertical scroll bar. how can i stop this from happening.
CONTEXT: editable HTML of https://code.google.com/apis/ajax/playground/?type=visualization#line_chart (using Firefox or Chorme).
Instructions for help you in the problem:
suppose you need a box with width=500px and height=400px.
check Javascript at new google.visualization.LineChart(), if the width and height inicializations are 500 and 400.
check if style of the HTML tag (perhaps div) of renderization place (id="visualization") is style="width: 800px; height: 400px;".
check if style of the HTML parent tag (any) of renderization place is bigger than 500 and 400, or is 100%.
Another solution is by "HTML cut": use overflow:hidden.
EXAMPLE OF CASE WITH SCROLL
// ... piece of your javacascript.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 800, height: 400,
vAxis: {maxValue: 10}}
);
} google.setOnLoadCallback(drawVisualization);
<!-- ... piece of your HTML -->
<div id="container" style="width:400px;overflow:scroll;">
<div id="visualization" style="width: 800px; height: 400px;"></div>
</div>
HTML SOLUTION (fix the container width)
<!-- ... piece of your HTML -->
<div id="container" style="width:800px;overflow:scroll;">
<div id="visualization" style="width: 800px; height: 400px;"></div>
</div>
ANOTHER SIMPLE HTML SOLUTION (use overflow:hidden)
<!-- ... piece of your HTML -->
<div id="container" style="width:400px;overflow:hidden;">
<div id="visualization" style="width: 800px; height: 400px;"></div>
</div>
... or reduce all, Javascript and HTML widths and heights, etc.
Using :
<script src="https://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1", {packages:["corechart"]});
var data = new google.visualization.DataTable();
//init your data
var options = {
width: "100%", height: "100%",
//other options
}
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
</script>
....
<body>
<div id="chart"></div>
</body>
You ensure that the graph will fit the div you're using.
Then to resize the graph set style="width: ...px; height: ...px;" with the desired size :
<body>
<div style="width: 800px; height: 400px;" id="chart"></div>
</body>

set two foreign key attribute as a composite primary key for another table in oracle

I'm having two column in STUDENTSINTEST table as
1.TestID
2.StudentID
both are foreign key for some tables, now i want to know how to set those two column as a composite primary for STUDENTSINTEST table? help are appreciated....
If your table has already been defined
alter table STUDENTSINTEST add constraint STUDENTSINTEST_PK primary key(TestID,StudentID);
else you can add the following statement to the CREATE TABLE statement
constraint STUDENTSINTEST_PK primary key(TestID,StudentID)
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.ArrayList" %>
<%# page import="com.otts.*" %>
<%# page import="com.otts.dao.TestProfile" %>
<%-- Variables declaration --%>
<link type="text/css" href="/TandQMgmt/css/menu.css" rel="stylesheet" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="menu.js"></script>
<link href="/TandQMgmt/css/style.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery.js" ></script>
<script src="../js/jquery-ui.js" ></script>
<script src="../js/jquery-validate.js" ></script>
<body>
<div class="contanier">
<div class="content-beginner">
<div class="logo"></div>
<div class="heading-bar">
<div class="heading-text"></div>
<div class="clear"></div>
</div>
</ul></div>
</li>
</ul></div>
</li>
<li class="last"><span>Help & Support </span></li>
</ul>
</div>
<div class="clear"></div>
<script>
$(function() {
$( "input:submit").button();})
function validateregisterform(){
$("form#Formviewtest").validate();
}
</script>
<%
if(request.getAttribute("indicator")=="view"){ %>
<p align="center">
<table width="800" height="281" border="1" bgcolor="#FFFFFF">
<tr>
<td height="33" colspan="7" bgcolor="#663300"><h1 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:16px; color:#FFF;">View Test Details</h1></td>
</tr>
<tr>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">TESTID</h2></td>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">TEST NAME</h2></td>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">TEACHER ID</h2></td>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">NO of PARTICIPANTS</h2></td>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">CURRENTLY ALLOCATED</h2></td>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">DURATION</h2></td>
<td width="96" bgcolor="#e3d5a8"><h2 style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:13px; color:#C30; text-align:center;">CREATED BY</h2></td>
</tr>
<%ArrayList userList=null;
userList=(ArrayList) request.getAttribute("totalResultSet");
for(int i=0;i<userList.size();i++)
{
TestProfile testProfile = (TestProfile) userList.get(i);
%>
<tr>
<td><%out.print(testProfile.getTestId());%></td>
<td><%out.print(testProfile.getTestName());%></td>
<td><%out.print(testProfile.getTeacherId());%></td>
<td><%out.print(testProfile.getNumberOfParticipants());%></td>
<td><%out.print(testProfile.getCurrentlyAllocated());%></td>
<td><%out.print(testProfile.getDuration());%> </td>
<td><%out.print(testProfile.getCreatedBy()); %> </td>
</tr>
<% }%>
</p>
</table>
<%}
else { %>
<form name="Formviewtest" id="Formviewtest" onsubmit="return validateregisterform()" action="../TestandQuestionManagement" method="post">
<pre>
<input type="submit" name ="Submit" value="View Test"></input>
</pre>
</div>
</div>
</div>
</form>
</body>
</html>
<%}%>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Do You wish to update test details?");
if (r==true)
{
alert("Test details updated!");
}
return false;
}
function validate(form){
var testName1 = form.testName.value;
var duration1 = form. duration.value;
var noofParticipants1 = form.noofParticipants.value;
var teacherId1 = form.teacherId.value;
if(testName1.length==0){
alert("Please enter a Test name");
return false;
}
if(testName1.length>10){
alert("Please enter a Test name lessthan or equal to 10");
return false;
}
if(duration1.length==0){
alert("Please enter a test duration");
return false;
}
if(duration1/1!=duration1){
alert("Please enter a test duration in numbers");
return false;
}
if(duration1<15 )
{
alert("Please enter a test duration greater than 15");
return false;
}
if(duration1>300 )
{
alert("Please enter a test duration less than 300");
return false;
}
if(noofParticipants1.length==0){
alert("Please enter a number of participants");
return false;
}
if(noofParticipants1/1!=noofParticipants1){
alert("Please enter a number of participants in numbers");
return false;
}
if(teacherId1.length==0){
alert("Please enter a Teacher Id");
return false;
}
if(teacherId1/1!=teacherId1){
alert("Please enter a teacher Id in numbers");
return false;
}
return true;
}
</script>
<title>Update test</title>
public static String DRIVERNAME="oracle.jdbc.driver.OracleDriver";
public static String SERVERNAME = "172.24.137.30";
public static String PORTNUMBER = "1521";
public static String SID = "ora10G";
public static String URL = "jdbc:oracle:thin:#" + SERVERNAME + ":" + PORTNUMBER + ":" + SID;
public static String USERNAME = "e554893 ";
public static String PASSWORD = "VAnjrmfvi";
Connection conn = null;
try {
// load the JDBC-ODBC Bridge driver
Class.forName(Constants.DRIVERNAME);
conn = DriverManager.getConnection(Constants.URL,
Constants.USERNAME, Constants.PASSWORD);
}
catch (Exception ex) {
System.out.println("Connection not created");
}
return conn;

OnMouseHover not working in Firefox

I have done an easy onmousehover effect and it works in all browsers, but firefox. I have stripped down the code to a bare minimum, but can't figure out whats wrong! Why doesn't the mouseover below work in firefox?
<!DOCTYPE html>
<html>
<head>
<style>
#box {
background:#222;
width:400px;
height:300px;
border-radius:5px;
}
#box_hover {
background:#555;
width:400px;
height:300px;
border-radius:5px;
}
</style>
<script type="text/jscript">
function mouseover() {
document.getElementById('box').id = 'box_hover';
}
function mouseout() {
document.getElementById("box_hover").id = 'box';
}
</script>
</head>
<body>
<div id="box" onmouseover="mouseover();" onmouseout="mouseout();"></div>
</body>
</html>
Firefox doesn't like "text/jscript". Try "text/javascript" instead.
see this link now this is work
<div id="box" onmouseover="mouseover();"></div>
and
#box {
background:#222;
width:400px;
height:300px;
border-radius:5px;
}
#box:hover {
background:#555;
width:400px;
height:300px;
border-radius:5px;
}
Besides the text/jscript issue, you can change your code like this: http://jsfiddle.net/RKKvt/
Please note that addEventListener does not work in older versions of Internet Explorer, and you need to resort to an hack (or drop it completely and go for the old element.onclick = function() { /* Do something here... */ }; way).
HTML
<div id='test'></div>
CSS
#test {
background-color: red;
height: 100pt;
width: 100pt;
}
JavaScript
document.getElementById('test').addEventListener('mouseover', function () {
this.setAttribute('style', 'background-color: green;');
}, false);
document.getElementById('test').addEventListener('mouseout', function () {
this.setAttribute('style', '');
}, false);

Resources