MVC Razor Validation not firing on textarea - asp.net-mvc

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.

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);
}
}

MVC Template editors and post

I'm at a beginner with ASP.NET MVC 4 and I have a problem. Basically I have this controller:
public ViewResult Login()
{
return View(new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
if (authProvider.Authenticate(model.LoginUserName, model.LoginPassword))
{
return Redirect(Url.Action("Index", "Home"));
}
TempData["message"] = "Nome utente e/o password errati!!!";
return View();
}
return View();
}
That implements a simple login view. I created also a ViewModel:
public class LoginViewModel
{
[Required(ErrorMessage = "Il nome utente è obbligatorio")]
[UIHint("TextBoxLogin")]
public string LoginUserName { get; set; }
[Required]
public string LoginPassword { get; set; }
}
Finally I created the EditorTemplate:
#model string
<input name="#ViewData.TemplateInfo.HtmlFieldPrefix" id="#ViewData.TemplateInfo.HtmlFieldPrefix"data-validation="required" data-validation-error-msg="#ViewData["HelpMessage"]" value="#Model" />
So far so good. The problem is in the view. If I put this in the view:
#using(Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.EditorForModel()
<p><input type="submit" value="Log in" /></p>
}
It works like a charm (but it puts a lot of not wanted html into the page), in fact, when I click on the submit button it goes to the POST actionResult of the controller. If I put this:
#using (Html.BeginForm("Login","Account",FormMethod.Post))
{
<p class="username">
<label for="UserName">Nome utente</label>
#Html.EditorFor(m => m.LoginUserName, new { HelpMessage = "Il nome utente è obbligatorio!!!" });
</p>
<p class="password">
<label for="Password">Password</label>
#Html.EditorFor(m => m.LoginPassword)
</p>
<p>
<input type="submit" value="Log in" />
</p>
}
It does not go on the post actionresult but always on the Get one. I want to put this type of code (the last one) in wich I can setup exactly the html but I want that it goes on the POST Actionresult, can someone help me to understand why?
-----------------update----------------
Here is the HTML generated:
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Title</title>
<meta name="robots" content="noindex,nofollow" />
<link href="/static/css/login.css" rel="stylesheet" type="text/css" />
<link href="/static/css/jquery_ui.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]><link href="/static/css/lt_ie9.css" rel="stylesheet" type="text/css" /><![endif]-->
<script src="/static/js/jquery_1_10_2.js"></script>
<script src="/static/js/jquery_ui.js"></script>
<script src="/static/js/jquery_ui_function.js"></script>
</head>
<body>
<form>
<div id="top">
<div class="wrapped">
<div id="logo">TITLE</div>
</div>
</div>
<div id="content" class="user_student">
<div class="wrapped">
<div class="login_intro">
<h2>TEST</h2>
</div>
<div class="login_input">
<p id="error_messages"></p>
<h2>THIS ONE MAKES GET REQUEST</h2>
<form action="/Account/Login" method="post"> <p class="username"><label for="UserName">Nome utente</label>
<!--<input id="UserName" name="UserName" type="text"/>-->
<input name="LoginUserName" id="LoginUserName"data-validation="required" data-validation-error-msg="Il nome utente è obbligatorio!!!" />;
</p>
<p class="password"><label for="LoginPassword">Password</label>
<input class="text-box single-line" data-val="true" data-val-required="Il campo LoginPassword è obbligatorio." id="LoginPassword" name="LoginPassword" type="text" value="" />
</p>
<p><input type="submit" value="Log in" /></p>
</form> <p class="hidden">old</p>
</div>
<div class="login_footer">
<p>FOOTER</p>
</div>
</div>
</div>
<h2>THIS ONE MAKE POST REQUEST</h2>
<form action="/Account/Login?ReturnUrl=%2f" method="post"><div class="editor-label"><label for="LoginUserName">LoginUserName</label></div>
<div class="editor-field"><input name="LoginUserName" id="LoginUserName"data-validation="required" data-validation-error-msg="" /> <span class="field-validation-valid" data-valmsg-for="LoginUserName" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="LoginPassword">LoginPassword</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Il campo LoginPassword è obbligatorio." id="LoginPassword" name="LoginPassword" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="LoginPassword" data-valmsg-replace="true"></span></div>
<p><input type="submit" value="Log in" /></p>
</form><script src="/static/form-validator/jquery.form-validator.min.js"></script>
<script src="/static/js/jquery_form_validator_function.js"></script>
</form>
</body>
</html>
Finally I figured out what is the problem...and of course it is the most stupid thing in the world.
In the rended code there is a open just after the body and, inside it, the form that MVC put from razor view.
Thanks for everyone for the help paricularly to #DavidG

MVC4 HTML.ValidationMessageFor is not showing validation messages

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

ASP.Net MVC3 Rendering partial action returns error

I have a problem while trying to render a partial action on my layout. On the line :
#{Html.RenderAction("Login");}
i get an error "CS1501: No overload for method 'Write' takes 0 arguments". I have tried also invoking the RenderPartial directly, with the same result... Can you tell me what is wrong?
The code of my partial view:
#model SikWebRole.Models.LogOnModel
<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 type="text/javascript">
$(document).ready(function () {
$('.LoginLink').click(function () {
$('#loginForm').submit();
});
});
</script>
#using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { id = "loginForm" }))
{
<div class="loginBox">
<div class="errorMsg">
#Html.ValidationSummary(true, "Błędny login/hasło.")
</div>
<div class="loginHolder">
<input type="text" class="textInput" name="UserName" value="Login" />
</div>
<div class="passwordHolder">
<input type="text" class="textInput" name="Password" value="Hasło" />
</div>
<input name="RememberMe" style="display:none;" type="hidden" value="true"/>
Zaloguj</span>
<ul><li class="registerLi">Zarejestruj</li><li class="RemindLi">Przypomnij hasło</li></ul>
</div>
}
The function used for render action:
public PartialViewResult Login()
{
return PartialView("LogOnForm", new SikWebRole.Models.LogOnModel());
}
The partial view I want to render belongs to the "LogOn" method which is from the Account Controller, and the Login method is in the Picture Controller, maybe this is the reason?
I would be glad for all the answers.
Best Regards
As requested this is the code of my Layout.cshtml: http://pastebin.com/He2Rp5P4
In your cshtml file use #Html.Partial, not #Html.RenderPartial.

How do I create a Html.EditorFor for my model in order to save time?

I currently only have the create view for my Album class:
#model MvcApplication1.Models.AlbumViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<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>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>AlbumViewModel</legend>
<p>
#Html.LabelFor(model => model.GenreId)
#Html.DropDownListFor(x => x.GenreId, new SelectList(Model.Genres, "GenreId", "name"))
</p>
<p>
#Html.LabelFor(model => model.ArtistId)
#Html.DropDownListFor(x => x.ArtistId, new SelectList(Model.Artists, "ArtistId", "Name"))
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I've been told that it's convention to use the EditorFor for both creating and editing in order to save time in the future.
So my view would end up looking like this:
#model MvcApplication1.Models.AlbumViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<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>
#Html.EditorForModel
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Is this correct? How and where do I declare and write this up in my solution?
Edit:
I have this in my main Account/Register view:
#model Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2>Register</h2>
<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>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>RegisterViewModel</legend>
#Html.EditorFor(model => model.RegisterModel)
#Html.EditorFor(model => model.Cities)
#Html.EditorFor(model => model.Countries)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And in my EditorTemplate:
#model Fooer.WebUI.Models.RegisterModel
THIS IS A TEST.
Yet it doesn't render that dummy text at all. It render the default controls for the model.
You would add your partial as a file under ~/Views/Shared/EditorTemplates/.
Brad Wilson's blog post on the subject of Custom object templates has all the information you need.
Change your view to as follows:
#model MvcApplication1.Models.AlbumViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<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>
#Html.EditorForModel()
<div>
#Html.ActionLink("Back to List", "Index")
</div>
this will output all properties of the model. Great post on its use here

Resources