MVC4 HTML.ValidationMessageFor is not showing validation messages - asp.net-mvc

I am trying to figure out ,why my validation messages are not showing up?
Here is my Razor page
#model MyViewModel
#{
Layout = "~/Views/Shared/_MainLayout.cshtml";
var listErrors = ViewBag.listErrors as Array;
}
<section class="selectconfiguration">
<h3 class="active">Add Rule</h3>
<div class="con-section">
#{Html.EnableClientValidation(true);}
#{Html.EnableUnobtrusiveJavaScript();}
#using (Html.BeginForm("AddRules", "Aliases", "HttpPost"))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td class="phone-options-label-column">
<div class="editor-label">
#Html.Label("Alias String:")
</div>
</td>
<td>
#Html.EditorFor(m => m.AliasString,new {#id="txtAliasString"})
</td>
<td> #Html.ValidationMessageFor(m => m.AliasString)</td>
</tr>
<tr>
<td class="options-label-column">
<div class="editor-label">
#Html.Label("Select an Associated Model:")
</div>
</td>
<td>
#Html.DropDownList("ddlModels", new SelectList(Model.Models, "Id", "Name", ""), "Unknown", new { #class = "mselectDDContItem" })
</td>
<td>
</td>
</tr>
</table>
}
<div>
<input type="submit" value="Add Rule" id="btnAddRule" name="AddRule" />
</div>
</div>
</section>
Here is my ViewModel
public class MyViewModel
{
[Required(ErrorMessage = "alias string required")]
[StringLength(30, ErrorMessage = "AliasString cannot be larger than 30 characters")]
public string AliasString { get; set; }
public IEnumerable<IParameter> Models { get; set; }
public string StatusMessage { get; set; }
}
On clciking the addRules button triggers my jquery clcik event
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddRule").click(function (e) {
e.preventDefault();
var params = {
'aliasString': $("#txtAliasString").val(),
'modelId': $("#ddlModels").val()
};
$.ajax({
url: "/Aliases/AddRules",
type: "POST",
dataType: 'json',
data: JSON.stringify(params),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
}).done(function () {
}).complete(function () {
}).success(function (dv) {
});
});
});
</script>
and I have these script references also on my layout page
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.treeview.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.selectmenu.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/global.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.nad.session.js")" type="text/javascript"></script>
<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/MicrosoftMvcValidation.js")"></script>
I dont understhnad why the validations are not firing.
If I click the button with the empty textbox also ,I can see post back happens and modelstate.isValid is returning true to the controller.

In my jquery button click function ,I added ,$('#myForm').valid() and then my validation started showing up.
$("#btnAddRule").click(function (e) {
if ($('#myForm').valid()) {
}
});

Just put submit button inside the form and validation would work

Related

Asp.net Mvc Ajax Record Couldn't find

i am creating the Asp.net MVC Project in Bank Balance Checking.if i enter the correct account no relevant balance want to display but not not displayed while i am running the programming i got the error was Additional information: The underlying provider failed on Open.
what i tried so far i attached below.
Index.cshtml
#{
ViewBag.Title = "Index";
}
<div class="row">
<div class="col-sm-8">
#using (Html.BeginForm("Index", "home", FormMethod.Post, new { id = "popupForm" }))
{
<table class="table table-bordered">
<caption> Add Products </caption>
<tr>
<th>Account No</th>
<th>Account Holder Name</th>
<th>Balance</th>
</tr>
<tr align="center">
<td>
<input type="text" class="form-control" placeholder="Account No" id="accno" name="accno" size="50px">
</td>
<td>
<input type="text" class="form-control" id="accname" size="25px" name="accname"
placeholder="price" disabled>
</td>
<td>
<input type="number" class="form-control" id="balance" name="balance"
placeholder="qty" size="25px" required>
</td>
</tr>
</table>
}
</div>
</div>
<hr />
#Scripts.Render("~/bundles/jquery")
#section scripts{
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<script>
getProductcode();
function getProductcode()
{
$("#accno").empty();
$("#accno").keyup(function (e) {
var q = $("#accno").val();
if ($('#accno').val().length === 0) {
$.alert({
title: 'Error!',
content: "Please Enter the Barcode",
type: 'red',
autoClose: 'ok|2000'
});
return false;
}
$.ajax({
type: "POST",
url: '/home/Getid?id=' + $("#accno").val(),
dataType: "JSON",
success: function (data)
{
console.log(data);
$('#accname').val(data.accname);
$('#balance').val(data.balance);
},
error: function (xhr, status, error)
{
// alert("The barcode entered is not correct");
}
});
return true;
});
}
</script>
}
#section styles{
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
}
HomeController
//you don't need this here except you want to use Dependency injection
bankEntities dc = new bankEntities();
public ActionResult Index()
{
return View();
}
public string accno { get; set; }
[HttpPost]
public JsonResult Getid(String Id)
{
var std = dc.accounts.Where(a => a.accno == Id).FirstOrDefault();
return Json(std, JsonRequestBehavior.AllowGet);
}
}

Datatable is not loading using Asp.net MVC

i am creating a simple crud system for my studies. I am a beginner of Asp.net MVC.i am tring to load the data from the database but i could do the task.what i tried so far i attached below. i am created database which name is skill and have a table course tried to load it dataTable.while run the progam i got the error of
Error
Uncaught TypeError: $(...).DataTable is not a function
at HTMLDocument.<anonymous> (Index:81)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)
Controller page
public ActionResult Index()
{
return View();
}
public ActionResult GetSkill()
{
using (skillEntities sk = new skillEntities())
{
var course = sk.courses.OrderBy(a => a.id).ToList();
return Json(new { data = course }, JsonRequestBehavior.AllowGet);
}
}
View Page
#{
ViewBag.Title = "Home Page";
}
<html>
<head>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div style="width:90%; margin:0 auto" class="tablecontainer">
<a class="popup btn btn-primary" href="/home/save/0" style="margin-bottom:20px; margin-top:20px;">Add New Employee</a>
<table id="myDatatable">
<thead>
<tr>
<th>ID</th>
<th>Course Name</th>
<th>Fee</th>
</tr>
</thead>
</table>
</div>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/home/GetSkill',
"type" : "get",
"datatype": "json"
},
"columns": [
{ "data": "id", "autoWidth": true },
{ "data" : "coursename", "autoWidth" : true},
{ "data": "fee", "autoWidth": true }
]
})
})
</script>
</body>
</html>
you have included jquery library twice, try removing below line, use min.js only
<script src="~/Scripts/jquery-3.4.1.js"></script>

Facing issue while submitting Partial View using JQuery post

I have an Area like below.
Controller Class
public class AdminController : Controller
{
//
// GET: /Admin/Admin/
[HttpPost]
public ActionResult Index_partialPost(AdminModule model)
{
return PartialView("_PartialPage1", model);
}
[HttpGet]
public ActionResult Index_partial()
{
return PartialView("_PartialPage1");
}
[HttpGet]
public ActionResult Index()
{
AdminModule model = new AdminModule();
model.MyName = "My Name";
return View("Index", model);
}
}
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<div id="myForm">
<p id="pid">
</p>
</div>
<input id="BTN" type="submit" value="Button" />
<script language="javascript" type="text/javascript">
$('#BTN').click(function(){
$('#pid').load("#Url.Action("Index_partial", "Admin")");
});
</script>
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript">
</script>
<div id="myForm">
<p id="pid">
</p>
</div>
<input id="BTN" type="submit" value="Button" />
<script language="javascript" type="text/javascript">
$('#BTN').click(function(){
$('#pid').load("#Url.Action("Index_partial", "Admin")");
});
</script>
Partial View
#model _1.Areas.Admin.Models.AdminModule
#using (Html.BeginForm())
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
<script language="javascript" type="text/javascript">
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin")';
$.post(url, null, function (data) {
});
});
</script>
Issue is - When trying to post the partial view using jQuery-post not working and giving 404. It's working with Ajax using below mentioned code of Partial View
#model _1.Areas.Admin.Models.AdminModule
#using (Ajax.BeginForm("Index", "Admin",
new AjaxOptions { UpdateTargetId = "myForm", HttpMethod = "Post" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
You should cancel the default action of the form by returning false from your click handler:
<script type="text/javascript">
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin")';
$.post(url, null, function (data) {
});
return false;
});
</script>
If you don't do that, the form is submitted to the server and the browser redirects to the target url leaving you absolutely no time for your AJAX request to ever execute.
Notice that it is much better to subscribe to the .submit event of the form in order to perform the AJAX request instead of the .click event of the submit button. The reason for this is obvious: there are other means to submit a form than clicking on a submit button. For example pressing the Enter key while inside an input field. If this happens your AJAX will never execute.
So here's the correct way. Start by giving an unique id to your form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
and then you could unobtrusively AJAXify this form:
<script type="text/javascript">
$('#myForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
}
});
return false;
});
</script>
I think you need to define the Area in the routeparameter where you do #Url.Action in your partial view:
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin", new { area = "Admin"})';
$.post(url, null, function (data) {
});
});
Else it will be posted to your main (root) Area where you probably don't have a AdminController...
You can doublecheck the url in the JS your HTML source when the form is rendered, it sould read "/Admin/Admin/Index_partialPost" instead of just "/Admin/Index_partialPost"

MVC Razor Validation not firing on textarea

i am having a problem with validating a form in MVC Razor the Binding class is the following based off an abstract class (there is no validation in the abstract class)
[GeminiDisplayName("You are about To reject the following Purchase Order", false)]
public class PORejected : PoApprovalItems
{
public PORejected() { }
[GeminiDisplayName("Rejection Reason")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Rejection Reason is Required")]
public string RejectReason { get; set; }
public override bool IsApproved
{
get
{
return false;
}
}
}
and the view is as follows
#model Gemini.Models.PORejected
#section Head{
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/PageScripts/_Approval.js")" type="text/javascript"></script>
}
#section TabHeader{
<li>Reject Approval for PO #Model.PO_Number</li>
}
#section TabContent{
#{
Html.EnableClientValidation();
}
<div id="ApprovalItem">
#{
#Html.ValidationSummary(false)
using (Html.BeginForm("Approve", "PO", FormMethod.Post))
{
#Html.Partial("Approval/ApprovalDetails", Model)
<div class="display-label">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="15%">
#Html.LabelFor(x => x.RejectReason)
</td>
<td>
#Html.TextAreaFor(x => x.RejectReason, new { #Class = "mceEditor required", #style = "width:60%;" })
#Html.ValidationMessageFor(x => x.RejectReason)
</td>
</tr>
</table>
<div style="float: right;">
<input type="button" value="Close" />
<input type="submit" value="Reject" />
</div>
</div>
Html.EndForm();
}
}
</div>
}
the thing is when i click the submit button it fires off before doing any validation even though it should validate
my question is what am i doing wrong?
UPDATED
found the answer eventually i was missing the following from the page.
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
found the answer eventually i was missing the following from the page. <script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
What is this line for?
Html.EnableClientValidation(false);
This disables client validation. Also, no need to set UnobtrusiveParameters on each view, set them once in web config.

Ajax.BeginForm(...) not always working, full postback sometimes, using ASP.NET MVC

I cannot for the life of me figure out why this postback sometimes does an ajax one as it is supposed to and sometimes it does not. Here is the relevant code:
JS:
<html>
<head>
<title>Index</title>
<link href="/Content/screen.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 8]><link href="/Content/ie.css" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/Content/plugins/fancy-type/screen.css" rel="stylesheet" type="text/css" />
<link href="/Content/plugins/buttons/screen.css" rel="stylesheet" type="text/css" />
<link href="/Content/plugins/link-icons/screen.css" rel="stylesheet" type="text/css" media="screen, projection" />
<link href="/Content/jQueryUI/css/cupertino/jquery-ui-1.8.9.custom.css" rel="stylesheet" type="text/css" />
<link href="/Content/HelpDesk.css" rel="stylesheet" type="text/css" />
<link href="/Content/droppy.css" rel="stylesheet" type="text/css" />
<link href="/Content/tablesorter.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.droppy.js" type="text/javascript"></script>
<script src="/Scripts/jquery.cascadingDropDown.js" type="text/javascript"></script>
<script src="/Scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(function () {
$('#nav').droppy();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#targetStartDate").datepicker();
$("#targetEndDate").datepicker();
$("#ticketsHTMLTable").tablesorter({ sortList: [[0, 0], [1, 0]] });
$(".fakeLink").mouseover(function () {
$(this).css("color", "red");
});
$(".fakeLink").mouseout(function () {
$(this).css("color", "black");
});
});
</script>
</head>
Here is my View (Razor):
#using (Ajax.BeginForm("Index", "Problem", new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "ticketsTable",
InsertionMode = InsertionMode.Replace
}))
{
<div class="notice">
<div class="prepend-1 span-2">
<label for="targetPriorityID">
Priority</label>
</div>
<div class="prepend-1 span-3">
<label for="targetStatusID">
Status</label>
</div>
<div class="span-3">
<label for="targetBusinessUnitID">
Business Unit</label>
</div>
<div class="span-3 prepend-1">
<label for="targetStartDate">
Start Date</label></div>
<div class="span-3 prepend-2">
<label for="targetEndDate">
End Date</label></div>
<div class="prepend-1 span-3 last">
&nbsp
</div> <div class="prepend-1 span-2">
#Html.DropDownList("targetPriorityID",
new SelectList(ViewBag.Priorities as System.Collections.IEnumerable,
"ID", "Title"), "All", new { #onchange = " this.form.submit();" })
</div>
<div class="prepend-1 span-3">
#Html.DropDownList("targetStatusID",
new SelectList(ViewBag.Statuses as System.Collections.IEnumerable,
"ID", "Title"),"All", new { #onchange="this.form.submit();" })
</div>
<div class="span-3">
#Html.DropDownList("targetBusinessUnitID",
new SelectList(ViewBag.BusinessUnits as System.Collections.IEnumerable,
"ID", "Title"), "All", new { #onchange = "this.form.submit();" })
</div>
<div class="span-3 prepend-1">#Html.TextBox("targetStartDate", "", new { onchange = "this.form.submit();" })</div>
<div class="span-3 prepend-2">#Html.TextBox("targetEndDate", "", new { onchange = "this.form.submit();" })</div>
<div class="prepend-1 span-3 last">
<input type="submit" value="Hide" />
</div>
<br />
<br />
<br />
</div>
}
<div id="ticketsTable">
#Html.Partial("_AllTickets", Model)
</div>
And finally the controller,
[HttpPost]
public ActionResult Index(int targetPriorityID = -1, int targetBusinessUnitID = -1, int targetStatusID = -1, string targetStartDate = "", string targetEndDate ="")
{
Repository<Priority> priorityRepository = new Repository<Priority>();
Repository<BusinessUnit> businessUnitRepository = new Repository<BusinessUnit>();
Repository<Status> statusRepository = new Repository<Status>();
ViewBag.Priorities = priorityRepository.GetAll();
ViewBag.BusinessUnits = businessUnitRepository.GetAll();
ViewBag.Statuses = statusRepository.GetAll();
var results = problemRepository.GetAll();
results = (targetPriorityID != -1) ? results.Where(t => t.PriorityID == targetPriorityID) : results;
results = (targetBusinessUnitID != -1) ? results.Where(t => t.BusinessUnitID == targetBusinessUnitID) : results;
results = (targetStatusID != -1) ? results.Where(t => t.StatusID == targetStatusID) : results;
results = (targetStartDate != "") ? results.Where(t => t.DateReported >= DateTime.Parse(targetStartDate)) : results;
results = (targetEndDate != "") ? results.Where(t => t.DateReported <= DateTime.Parse(targetEndDate)) : results;
if (Request.IsAjaxRequest())
{
return PartialView("__AllTickets", results);
}
return View(results);
}
Any thoughts?
I would suggest you to use normal form that will be AJAXified later:
#using (Html.BeginForm("Index", "Problem")
{
<div class="notice">
<div class="prepend-1 span-2">
<label for="targetPriorityID">Priority</label>
</div>
<div class="prepend-1 span-3">
<label for="targetStatusID">Status</label>
</div>
<div class="span-3">
<label for="targetBusinessUnitID">Business Unit</label>
</div>
<div class="span-3 prepend-1">
<label for="targetStartDate">Start Date</label></div>
<div class="span-3 prepend-2">
<label for="targetEndDate">End Date</label>
</div>
<div class="prepend-1 span-3 last">
&nbsp
</div>
<div class="prepend-1 span-2">
#Html.DropDownList("targetPriorityID", new SelectList(ViewBag.Priorities as System.Collections.IEnumerable, "ID", "Title"), "All")
</div>
<div class="prepend-1 span-3">
#Html.DropDownList("targetStatusID", new SelectList(ViewBag.Statuses as System.Collections.IEnumerable, "ID", "Title"), "All")
</div>
<div class="span-3">
#Html.DropDownList("targetBusinessUnitID", new SelectList(ViewBag.BusinessUnits as System.Collections.IEnumerable, "ID", "Title"), "All")
</div>
<div class="span-3 prepend-1">
#Html.TextBox("targetStartDate", "")
</div>
<div class="span-3 prepend-2">
#Html.TextBox("targetEndDate", "")
</div>
<div class="prepend-1 span-3 last">
<input type="submit" value="Hide" />
</div>
<br />
<br />
<br />
</div>
}
<div id="ticketsTable">
#Html.Partial("_AllTickets", Model)
</div>
and then in a separate file AJAXify it:
$(function() {
$('form :input').change(function() {
var form = $('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
$('#ticketsTable').html(result);
}
});
});
});
Another improvement I that I would suggest you is to use view models and get rid of ViewData and use strongly typed helpers.
One problem I can see is that your AJAX options in your Razor view specify the GET HTTP method, but the action filter on the controller action specifies POST.
I wonder if Request.IsAjaxRequest() is causing the problem. I would look at removing that code and always return PartialView("__AllTickets", results); instead.

Resources