set two foreign key attribute as a composite primary key for another table in oracle - 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;

Related

Why is the string not added to the property via Model.addObject?

I created #ControllerAdvice to handle BindException:
#ControllerAdvice
class globalControllerAdvice {
#ExceptionHandler(BindException.class)
public ModelAndView handleMyException(HttpServletRequest req, Exception e) {
ModelAndView model = new ModelAndView();
model.addObject("myerror",e.getErrCode());
model.addObject("message",e.getMessage());
model.addObject("exception","bind exception");
model.setViewName("error");
return model;
}
}
And created error.html :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table td{
vertical-align:top;
border:solid 1px #888;
padding:10px;
}
</style>
</head>
<body>
<h1>Error Page</h1>
<table>
<tr>
<td>Error</td>
<td th:text="${myerror}"/>
</tr>
<tr>
<td>Message</td>
<td th:text="${message}"/>
</tr>
<tr>
<td>Exception</td>
<td th:text="${exception}"/>
</tr>
</table>
</body>
</html>
And when executing, when I make a mistake on purpose, the page appears normally,but the properties are not filled in .That is, a table is created, but the text "${myerror}" , "${message}" , "${exception}" are not filled in with e.getErrCode() , e.getMessage() ,
"bind exception". Can anyone tell me what the problem is? thanks

Google Picker Search only inside parent folder

I am using setParent() to show a particular folder only in Google picker but searching lists all the files and folders. I want search results restricted to parent folder.
Is this possible?
As far as I can tell there is no way to do this with the picker API. One hack is to filter for starred files but that is usually not helpful because you probably just want to set one directory/folder to search inside.
In the end I had to use the Google Drive API instead and create my own interface
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js" integrity="sha512-RNLkV3d+aLtfcpEyFG8jRbnWHxUqVZozacROI4J2F1sTaDqo1dPQYs01OMi1t1w9Y2FdbSCDSQ2ZVdAC8bzgAg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body style="background-color: rgb(221, 238, 232);">
<div style="max-width: 1100px; margin: auto;" class="conainer mt-5">
<div class="row text-center mt-5">
<div class="col-10 ms-5">
<div class="d-flex">
<input type="search" class="form-control me-2" id="search_input" oninput="search(event)" placeholder="Search" aria-label="Search">
<button type="button" class="btn btn-primary" oninput="search(event)">
<i class="fas fa-search"></i>
</button>
</div>
</div>
<div class="row text-center mt-5 ">
<div class="col-10 ms-5" style="background-color: white; border-radius: 5px;">
<template type="text/x-handlebars-template" id="documentsTemplate">
<div class="row mt-2 mb-2">
{{#if documents.length}}
{{#each documents}}
<div class="col-2 mt-2">
<div style="height: 200px; width:150px; background-color: white; border-radius: 5px; border: solid 1px; border-color: lightblue;">
<img style="height: 150px; width:150px;" src="{{thumbnailLink}}" />
<input class="form-check-input" type="checkbox" value="">
{{name}}
</div>
</div>
{{/each}}
{{else}}
<div style="height: 200px; width:100%; background-color: white; text-align: center; font-size: 2vw; margin: 0 auto;">
No Results
</div>
{{/if}}
</div>
</template>
<div id="documentsList"></div>
</div>
</div>
</div>
</div>
<script type="module" src="script.js"></script>
<!-- <script src="https://apis.google.com/js/platform.js"></script> -->
<script src="https://apis.google.com/js/api.js"></script>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
//script.js
//import { google_client_id } from "./utils/configs.js"
// get this from 'APIs and Services'>credentials>Oauth app
const google_client_id=XXXXX
(function() {
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth2', onAuthApiLoad);
gapi.load('picker', onPickerApiLoad);
}
globalThis.search = (event) => {
clearTimeout(globalThis.searchTimeout);
globalThis.searchTimeout = setTimeout(() => {
getTemplateFolder()
.then(searchFiles)
}, 1000)
}
document.getElementById('search_input').addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
var key = event.key || event.keyCode;
if (key === 13) {
// Cancel the default action, if needed
event.preventDefault();
search(event);
}
});
gapi.load('client:auth2', (aa) => {
gapi.client.init({
client_id: google_client_id,
scope: 'https://www.googleapis.com/auth/drive',
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"],
})
.then(checkSession)
.then(function() {
return getTemplateFolder();
})
.then(function(folder) {
return getFiles(folder);
});
});
function checkSession() {
if (!gapi.auth2.getAuthInstance().isSignedIn.get()) {
return gapi.auth2.getAuthInstance().signIn();
}
}
function getTemplateFolder() {
return gapi.client.drive.files.list({
q: "mimeType = 'application/vnd.google-apps.folder' and name = 'XXXXXX' and trashed = false",
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}).then(function(response) {
console.log(response);
return response.result.files[0];
});
}
function getFiles(templateFolder) {
return gapi.client.drive.files.list({
q: `'${templateFolder.id}' in parents and trashed = false`,
pageSize: 10,
fields: 'nextPageToken, files(id, name, mimeType, thumbnailLink)',
}).then(function(response) {
console.log(response);
var template = Handlebars.compile(document.querySelector("#documentsTemplate").innerHTML);
document.querySelector("#documentsList").innerHTML = template({ documents: response.result.files });
return response.result.files;
});
}
function searchFiles(templateFolder) {
return gapi.client.drive.files.list({
q: `'${templateFolder.id}' in parents and fullText contains '${document.getElementById("search_input").value}' and trashed = false`,
pageSize: 10,
fields: 'nextPageToken, files(id, name, mimeType, thumbnailLink)',
}).then(function(response) {
console.log(response);
var template = Handlebars.compile(document.querySelector("#documentsTemplate").innerHTML);
document.querySelector("#documentsList").innerHTML = template({ documents: response.result.files });
return response.result.files;
});
}
})();
Make sure to add the google_client_id and the directory name you want to filter by.

Python and Scrapy doesn't work well with malformed HTML

I was trying to crawl a website which has badly formatted HTML web pages. Take some web page as an example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="keywords" content="physician, doctor, CME, CE, physician job recuiter, Chinese speaking doctors, medical school alumni," />
<meta name="description" content="An online database for physicians who obtained medical degree in China and are practicing in USA. It contains over 6,000 profiles. Email:admin#cmgforum.net for any question." />
<title>
CMG Physician Database - 华人医生数据库
</title>
<link rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-27283808-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript">
function validateForm()
{
valid = true;
if ( document.myForm.last.value == "" )
{
alert ( "Last name is required" );
valid = false;
}
else if ( document.myForm.first.value == "" )
{
alert ( "First name is required" );
valid = false;
}
else if ( document.myForm.states.value == "" )
{
alert ( "State is required" );
valid = false;
}
else if ( document.myForm.specialty_id.value == "" )
{
alert ( "Specialty is required" );
valid = false;
}
else if ( document.myForm.gradschool_id.value == "" )
{
alert ( "School is required" );
valid = false;
}
return valid;
}
</script>
<script type="text/javascript">
if (screen.width<800) {
window.location="http://physician.cmgforum.net/m/";
}
</script>
<script language="JavaScript"
type="text/JavaScript">
function changePage(newLoc)
{
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
</script>
</head>
<body>
<div id="outer">
<div id="upbg"></div>
<div id="inner">
<div id="header">
<embed src="flash/cmglogo.swf" width="685" Height="90">
</div>
<div id="menu">
<center>
<ul>
<li>Home</li>
<li>Combo Search</li>
<li>Name</li>
<li>Schools</li>
<li>Specialties</li>
<li>Local Specialties</li>
<li>States</li>
<li>Cities</li>
</center>
</div>
<table width="100%">
<tr>
<td width="2%"></td>
<td>
<form method="POST" name="menu" >
<select name="selectedPage"
onChange="changePage(this.form.selectedPage)">
<option value = "" selected>Site Navigation</option>
<option value = "/index.php">Home</option>
<option value = "/facilities.php"> Medical Facilities</option>
<option value = "/stats-d.php">Statistics</option>
<option value = "/contact.php">Contacts</option>
<option value = "/top5.php">The Top5</option>
<option value = "http://blog.cmgforum.net">Blog</option>
<option value = "/links.php">Links</option>
<option value = "/addme.php">Add Me</option>
<option value = "/news.php">News</option>
<option value = "/faq.php">FAQ</option>
<option value = "/pop-d.php">人气</option>
<option value = "/pgy-d.php">PGY</option>
<option value = "/video2-d.php">CMG Videos</option>
<option value = "/url.php">CMG Website</option>
</select>
</form>
</td>
<td>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6867265085889194";
/* header-links */
google_ad_slot = "9503010667";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td>
</tr></table>
</body>
</html>
<center>
<table><tr>
<td width="5%"></td>
<td>
<center>
<script type="text/javascript"><!--
google_ad_client = "pub-6867265085889194";
/* 468x60, created 8/19/10 */
google_ad_slot = "1699885909";
google_ad_width = 400;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</center>
</td>
<td>
<img src="images/code.jpg" alt="QR Code" height="60" width="60">
</td>
</tr></table>
</center>
<!---
<marquee ALIGN="Top" LOOP="infinite" BGCOLOR="#FFFFFF" DIRECTION="left" HEIGHT=16 WIDTH=640 scrollamount="3" scrolldelay="1"><FONT SIZE="3" FACE="courier" COLOR=blue>
第三届健桥医学峰会即将在波士顿召开, 更多的信息请点击这里!
</font></marquee>
--->
<table width="100%" style="text-shadow: 1px 1px 3px #999;"><tr><td width="3%"></td><td width="16%">Allergy & Immunology(20)<br>Anesthesiology(595)<br>Cardiology(129)<br>Dentistry(437)<br>Dermatology(29)<br>Emergency Medicine(8)<br>Endocrinoloy(60)<br>Family Practice(434)<br>Gastroenterology(88)<br>General Surgery(94)<br>Geriatric Medicine(48)<br>Hem/Onc(295)<br>Infectious Disease(12)<br>Internal Medicine(1880)<br>Medical Genetics(47)<br><br></td><td width="3%"></td><td width="16%">Nephrology(114)<br>Neurology(333)<br>Neurosurgery(11)<br>OB/GYN(83)<br>Occupational Med(33)<br>Ophthalmology(63)<br>Optometry(28)<br>Orthopaedics(18)<br>Otolaryngology(10)<br>Pathology(1235)<br>Pediatrics(300)<br>Pediatric Hem/Onc(8)<br>Pediatric Cardiology(9)<br>Pediatric GI(9)<br>Pediatric Neurology(13)<br><br></td><td width="3%"></td><td width="17%">Pediatric Endocrinology(10)<br>Pediatric Rheumatology(2)<br>Pediatric Allergy(Immu)(5)<br>Plastic Surgery(5)<br>Psychiatry(319)<br>Pulmonary Disease(30)<br>Radiation Oncology(54)<br>Diag Radiology(Nuclear)(156)<br>Rehabilitation(216)<br>Sports Medicine(2)<br>Rheumatology(43)<br>Thoracic Surgery(17)<br>Urology(12)<br>Add New Specialty<br>Add New Specialty<br><br></td><td width="3%"></td><td width="20%"><script type="text/javascript"><!--
google_ad_client = "ca-pub-6867265085889194";
/* spe-120-240 */
google_ad_slot = "2416199460";
google_ad_width = 120;
google_ad_height = 240;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br>
</td></tr></table><div id="top5">
<html>
<head>
<link rel="stylesheet" type="text/css" href="default.css" />
</head>
<body>
<center>
<div id="ad">
<script type="text/javascript"><!--
google_ad_client = "pub-6867265085889194";
/* 728x90, created 8/26/10 */
google_ad_slot = "7083487992";
google_ad_width = 715;
//google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
</center>
</body>
</html>
</div>
<center>
<table border="0" BORDERCOLOR=orange><tr>
<td><div style="padding: 2px; border: 1px red solid;"></div></td>
<td><img src="http://physician.cmgforum.net/images/wikilips.jpg" border="1" width="160" height="80"></td>
<td><img src="http://physician.cmgforum.net/images/MedicalCareer_150x65.gif" border="1" width="170" height="80"></td>
<td><img src="http://physician.cmgforum.net/images/scan.JPG" border="0" width="80" height="80">
<img src="http://physician.cmgforum.net/images/qrcode.png" border="0" width="80" height="80">
</td>
</tr></table>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>terrafirma1.0 by nodethirtythree</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="stylesheet" type="text/css" href="default.css" />
</head>
<body>
<center>
<div id="footer">
© copyright 2007 cmgforum.net. all rights reserved.
Contact: admin#cmgforum.net
</div>
</div>
</div>
</body>
</html>
As we can see from this, there are two root elements here. In such case, Scrapy can't parse the XPath correctly. Any ideas how to handle this?
When you face malformed HTML pages, try to generalize your xpaths since the browser and scrapy don't interpret the page in the same way. In this case, if you want to extract the list of links in the table, try an xpath like this:
//tr//td//a[contains(#href,'/specialty/')]

How to add required field in MVC3 ? (Not using Model)

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.

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"

Resources