mvc 3 - ajax.begin form and partial view on httppost - asp.net-mvc-3

I have a problem with partialView, cant load parital view after post with Ajax.PostBack. When i click submit button a partialView render as View not as a partial. This is my controller:
[HttpPost]
public PartialViewResult UpdatePersonalData(UserLine user)
{
var usr = um.GetUserByLoginMapper(User.Identity.Name);
ViewBag.Regions = rm.GetAllRegionsMapper().ToList();
if (ModelState.IsValid)
{
return PartialView("getLabelsPersonalData", usr);
}
return PartialView("getPersonalData", user);
}
public PartialViewResult getPersonalData()
{
ViewBag.Regions = rm.GetAllRegionsMapper().ToList();
var user = um.GetUserByLoginMapper(User.Identity.Name);
return PartialView("getPersonalData", user);
}
public PartialViewResult getLabelsPersonalData()
{
var user = um.GetUserByLoginMapper(User.Identity.Name);
return PartialView("getLabelsPersonalData", user);
}
getPersonalData.cshtml - partialView
#model MasterProject.JobForYouFinal.BO.UserLine
#using (Ajax.BeginForm("UpdatePersonalData", new AjaxOptions
{
UpdateTargetId = "personalDataContent",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
<table style="text-align:center; margin:0 auto;">
<tr>
<td>#Html.LabelFor(a => a.PersonalData.Name)</td>
<td>#Html.EditorFor(a => a.PersonalData.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.LastName)</td>
<td>#Html.EditorFor(a => a.PersonalData.LastName)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.Address.PostCode)</td>
<td>#Html.EditorFor(a => a.Address.PostCode)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.KeyWord)</td>
<td>#Html.EditorFor(a => a.PersonalData.KeyWord)</td>
</tr>
<tr>
<td><input id="save" type="submit" value="Zapisz" /></td>
<td>#Ajax.ActionLink("Anuluj", "getLabelsPersonalData", new AjaxOptions {
UpdateTargetId = "personalDataContent",
InsertionMode = InsertionMode.Replace
})</td>
</tr>
<tr>
<td>#Html.ValidationSummary()</td>
</tr>
</table>
}
getLabelPersonalData.cshtml - partialView
#model MasterProject.JobForYouFinal.BO.UserLine
<table class="myAccountTable">
<tr>
<td>#Html.LabelFor(a => a.RegistrationDate)</td>
<td>#Html.DisplayFor(a => a.RegistrationDate)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.Name)</td>
<td>#Html.DisplayFor(a => a.PersonalData.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.LastName)</td>
<td>#Html.DisplayFor(a => a.PersonalData.LastName)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.PersonalData.KeyWord)</td>
<td>#Html.DisplayFor(a => a.PersonalData.KeyWord)</td>
</tr>
<tr>
<td colspan="2"><input id="personalDataButton" type="submit" value="Edytuj" /></td>
</tr>
</table>
index.cshtml = glowny widok
<div class="empAccountSectionContainer">
<div id="personalDataHeader" class="empAccountSectionHeader">Dane personalne</div>
#using (Ajax.BeginForm("getPersonalData", new AjaxOptions
{
UpdateTargetId = "personalDataContent",
InsertionMode = InsertionMode.Replace
}))
{
<div id="personalDataContent" class="empAccountSectionBody">
#{Html.RenderPartial("getLabelsPersonalData", Model.User);}
</div>
}
</div>
Trying fix this issue with some onSuccess function:
<script type="text/javascript">
function onSuccess() {
$('#personalDataContent').load('EmployeeAccount/getLabelsPersonalData');
}
</script>
this is my layout imports
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/start/jquery-ui.css" rel='stylesheet' type='text/css'>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js"></script>
<script str="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-1.7-development-only.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/jquery-ui.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmplPlus.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>
<script str="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.min.js"></script>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Styles.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.8.22.custom.css")" rel="Stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery.ui.dialog.css")" rel="Stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery.ui.theme.css")" rel="Stylesheet" type="text/css" />
</head>
I had to pust this:
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
in my partialView, becouse validation not worked. Now validation working fine, but when model is valid, cant load partial view as partial.
But still no results. Please help.

I know this is an old question, but I had the same problem. I solved it using the code belowe in my view:
#{
Layout = Request.IsAjaxRequest()?null:"~/Views/Shared/Layout.cshtml";
}
I don't know if this solution is the best one, but it surely works ;-)

Related

display data from io.socket in Slickgrid

I receive data from io.socket and I would like to put the data in an array of object so this can be displayed in the slickgrid. For some reason the data pushed in the info is empty. Could somebody help me with this?
Thanks!!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid</title>
<link rel="stylesheet" href="/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="/examples/examples.css" type="text/css"/>
</head>
<body>
<table width="100%">
<tr>
<td valign="top" width="50%">
<div id="myGrid" style="width:600px;height:500px;"></div>
</td>
<td valign="top">
<h2>Demonstrates:</h2>
<ul>
<li>basic grid with minimal configurations</li>
</ul>
<h2>View Source:</h2>
<ul>
<li> View the source for this example on Github</li>
</ul>
</td>
</tr>
</table>
<script src="/lib/jquery-1.7.min.js"></script>
<script src="/lib/jquery.event.drag-2.2.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/slick.core.js"></script>
<script src="./slick.grid.js"></script>
<script>
var grid;
var info;
var info= [];
var columns = [
{id: "completed", name: "completed", field: "completed"},
{id: "createdAt", name: "createdAt", field: "createdAt"},
{id: "id", name: "id", field: "id"},
{id: "title", name: "title", field: "title"},
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
jQuery(function($){
var socket = io.connect();
socket.on('new message', function(data){
$.each(data, function(idx, obj) {
info.push(obj);
});
})
});
grid = new Slick.Grid("#myGrid", info, columns, options);
</script>
</body>
</html>
When you update the data behind slickgrid you need to tell the grid to redraw with the new data:
socket.on('new message', function(data){
$.each(data, function(idx, obj) {
info.push(obj);
});
grid.invalidate(); // not 100% sure this is needed....
grid.render();
})

How to pass value from view to controller

In controller i have function public ActionResult Index(int id,int test= 0,int to=10){} I try to change value test from view on click to get test+=10 but i dont know how. I tryed with action link and ajax but its not working. Any ideas?
My view code :
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<title>Countries</title>
<link href="~/Content/style.css" rel="stylesheet" />
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<table>
<tr>
<td><h3>Matches</h3></td>
</tr>
<tr>
</tr>
#foreach (var i in Model.ListMatch)
{
<tr>
<td>#Html.ActionLink(i.Description, "", new { id = i.Id })</td>
</tr>
}
</table>
</div>
</body>
</html>
I return results to ng-view. Can i do something like
This question isn't explained very well, but from what I gather you want to be able to make a change to a value without reloading the page or leaving that view.
In order to do this you have to use AJAX. I know you said you tried AJAX but perhaps you got something wrong. Try this:
$('#yourbutton').click(function() {
$.post( "/YourController/YourFunction", function() {
alert( "success" );
});
});

How to refresh PartialView by calling ActionLink in Grid in PartialView

I have a PartialView, that contains grid. The grid has a list of files that can be deleted. After user deletes the file I return PartialView with new file list.
Issue:
The new screen contains ONLY the PartialView. The MenuItems and all other things on the page are NOT rendered.
Any help highly appreciated. Thank you...
MY code:
Sellers.cshtml
'ACSDemoWinAzureACS.Models.SellersModel
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-2.1.0.min.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<div id="gridContainer">
#Html.Partial("_AdminView", Model)
</div>
'
_AdminView.cshtml - The PartialView
#model ACSDemoWinAzureACS.Models.HomeModel
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-2.1.0.min.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<div id="gridMain">
#using (Html.BeginForm("Admin", "Home", new { enctype = "multipart/form-data" }))
{
foreach(var file in Model.files)
{
<tr>
<td> #file.FileName</td>
<td>#Ajax.ActionLink("Delete" , "Delete" , "Home",
new { id = file.FileName },
new AjaxOptions
{
UpdateTargetId="gridMain", // <-- DOM element ID to update
InsertionMode = InsertionMode.Replace, // <-- Replace the content of DOM element
HttpMethod = "GET" // <-- HTTP method
})
</td>
</tr>
}
}
</div>
HOmeController.cs
public PartialViewResult Delete(string id)
{
_model.Delete(id);
_model.files = _model.GetFiles();
return PartialView("_AdminView",_model);
}

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/')]

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