When use IEnumerable in view client side validation is not working? - asp.net-mvc-3

I am passing List from Model to view , so I specified in view like this
IEnumerable. In this situation Client side validation is not firing
View :
#model IEnumerable<ShoppingCart.Models.ShoppingClass>
#{
ViewBag.Title = "Display";
}
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#Html.ValidationSummary(true)
#using (Html.BeginForm())
{
<table>
<tr>
<td>#Html.Label("BrandName")
</td>
<td>#Html.TextBox("BrandName")
<div>
#Html.ValidationMessage("BrandName")</div>
</td>
<td>
<input type="submit" value="Search" name="Search" />
</td>
</tr>
</table>
}

What you've written is wrong.
You're got the view strongly typed but then you're not using the strongly typed properties or validation messages. Also, you've got the validation summary outside the form.. which won't work.
#using (Html.BeginForm())
#Html.ValidationSummary(true)
Then, you'll need to do something like this:
<table>
#foreach (ShoppingClass shoppingClass in Model) {
<tr>
<td>#Html.LabelFor(x => x.BrandName)
</td>
<td>#Html.TextBoxFor(x => x.BrandName)
<div>
#Html.ValidationMessageFor(x => x.BrandName)</div>
</td>
</tr>
}
</table>
<input type="submit" value="Search" name="Search" />
I'm not sure why you have a Search button for every item that goes to the same controller and action.. but I'll leave that for you to figure out.

Related

while name mvc3 form with #Html.BeginForm() it display form fields between System.Web.Mvc.Html.MvcForm {} in explorer

I am working in ASP.NET MVC3 and creating a form:
#Html.BeginForm(null, null, FormMethod.Post, new { name = "frmAcnt", id = "frmAcnt" })
Because I dont want to give action and controller name. It works fine but in Firefox or any other browser it shows form between these two lines. What can I do for remove it from display?
System.Web.Mvc.Html.MvcForm {
}
and in the page source this line is showing
<form action="/Home/AccCode" id="frmAcnt" method="post" name="frmAcnt">System.Web.Mvc.Html.MvcForm
below is my view
#model CBS.Models.AccntBD
#{
ViewBag.Title = "AccCode";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AccCode</h2>
<div>
#Html.BeginForm(null, null, FormMethod.Post, new { name = "frmAcnt", id = "frmAcnt" })
{
<table class="tablestyle">
<tr>
<td>
<input type="text" id="AcCode" name="AcCode" maxlength="10" placeholder="Account Code" autofocus="true" class="required" />
</td>
</tr>
<tr>
<td>
<label>Description</label>
</td>
<td>
<input type="text" id ="Descrip" name="Descrip" maxlength="150" placeholder="Desription..." class="Descrip"/>
</td>
</tr>
<tr>
<td>
<span>
<input type="button" name="clear" value="Cancel" onclick="clearForm(this.form);" >
</span>
<span>
<input type="submit" id="sve" name="action" value="Save" />
</span>
<span>
<input type="button" id="edi" value="Edit" name="action"/>
</span>
<span>
<input type="button" value="Delete" id="del" name="action"/>
</span>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
}
</div>
Try this once and ideally you can use #using (Html.BeginForm()){ } to define form
View
#using (Html.BeginForm(null, null, FormMethod.Post, new { name = "frmAcnt", id = "frmAcnt" }))
{
#* Your Form Content Here *#
}
HTML Output is
<form name="frmAcnt" method="post" id="frmAcnt" action="/"></form>

Tablesorter with pagination affects partial view data

I am using tablesorter with pagination functionality in my partial view. The partial view is loading using ajax in view page to prevent refreshing of page. If I apply only tablesorter it works fine. But when I apply pagination with tablesorter it does not give proper output.
I have drop down list in my page and when I select value in drop down list it load data perfectly and sorting and pagination works fine as below :
But When 2nd time I select another value from drop down list. Data is not getting display.
If I only use tablesorter without pagination It works fine each time I select different value in dropdown.
What Can be reason for this?
this is my view page code :
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Search MDLNoWise
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<fieldset>
<legend>Search by MDLNo</legend>
<div id="search">
<br /><br />
Select MDLNo
<%:
Html.DropDownListFor(
model => model.Request_For_Id,
ViewData["MDLno"] as SelectList, "--Select--", new {id ="Request_For_Id" })
%>
<br /><br />
<div id="viewlist">
</div>
</div>
</fieldset>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
<link href="../../Content/Styles/blue.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$('#Request_For_Id').change(function () {
var mdlno = document.getElementById("Request_For_Id").value;
$.ajax({
url: '/Search/MDLNoDataList/',
type: "POST",
data: {
id: mdlno
},
dataType: "html",
success: function (data) {
$("#viewlist").html(data);
},
error: function () {
alert("No Records Found");
//$("#viewlist").html('No Records Found');
}
});
});
});
</script>
</asp:Content>
this is my partial view in which I use tablesorter with pagination.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>>" %>
<%--<script src="#Url.Content("../../Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("../../Scripts/jquery.tablesorter.js")" type="text/javascript"></script>
<script src="#Url.Content("../../Scripts/jquery.tablesorter.pager.js")" type="text/javascript"></script>--%>
<script src="../../Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.tablesorter.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.tablesorter.pager.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("table.tablesorter").tablesorter()
.tablesorterPager({ container: $("#pager"), size: $(".pagesize option:selected").val() });
});
</script>
<div>
<table class="tablesorter">
<thead>
<tr>
<th>
Request_For_Id
</th>
<th>
Territory
</th>
<th>
Estimated_Amount
</th>
<th>
Actual_Amount
</th>
<th>
Date_Created
</th>
<th>
Compute_CRM_State
</th>
<th>
Compute_Event_Type
</th>
</tr>
</thead>
<tbody>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: Html.DisplayFor(modelItem => item.Request_For_Id)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Territory)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Estimated_Amount)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Actual_Amount)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Date_Created)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Compute_CRM_State)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Compute_Event_Type)%>
</td>
</tr>
<%} %>
</tbody>
</table>
<div id="pager" style="position: none;">
<img src="../../Content/images/first.png" class="first" />
<img src="../../Content/images/prev.png" class="prev" />
<input type="text" class="pagedisplay" />
<img src="../../Content/images/next.png" class="next" />
<img src="../../Content/images/last.png" class="last" />
<select class="pagesize">
<option selected="selected" value="1">1</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</div>
</div>

How to get objec it in Kendo Grid and pass it into button in gridrow

I'm trying to put a button into grid. In order to achieve that I wanted to use rowTemplates. However I have a problem with geting and item id and put it into action parameter.
So far I tried these constructinos
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr>
<td>
<form action="/Home/EditProduct/?id="+ "#=Id#" class="addEditButton" method="post">
<submit type="button" value="Edytuj"/>
</form>
</td>
</tr>
</script>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr>
<td>
<form action="/Home/EditProduct/?id="+ ${ Id } class="addEditButton" method="post">
<submit type="button" value="Edytuj"/>
</form>
</td>
</tr>
</script>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr>
<td>
<form action="/Home/EditProduct/?id=${ Id }" class="addEditButton" method="post">
<submit type="button" value="Edytuj"/>
</form>
</td>
</tr>
</script>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr>
<td>
<form action="/Home/EditProduct/?id=${ Id } class="addEditButton" method="post">
<submit type="button" value="Edytuj"/>
</form>
</td>
</tr>
</script>
However non of this method can successfully retrieve value of id parameter from object bounded to row. Is it possible to somehow pass value of id into action ??
I think this will answer your question.
http://andregelderblom.wordpress.com/2012/02/27/pass-kendoui-datagrid-variable-to-template-that-uses-zend-url/

MVC3 Razor script reloading issue even with unobtrusive

Even using the unobtrusive ajax library, the scripts loaded into this page from the _Login.cshtml file are loaded when the form is submitted and I do not know how to prevent this. An even stranger effect is when an onclick event is applied to any element, when the form is submitted the script gets executed by the number of times the element was clicked.
Edit
On further testing, I realized that the unobtrusive ajax library basically re-loads the whole page inside the UpdateTargetId element, which is VERY counterproductive. This means if I submit the page 4 times, the page is loaded subsequently within each UpdateTargetId element, on each page within the page. What am I doing wrong? Is that what it's supposed to do?
#using MinervaMvc.App_Data
#model MinervaMvc.Models.LogOnModel
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Login.cshtml";
}
<div id="loginContainer">
<h2>
Login</h2>
<div id="loginForm">
#{Html.EnableClientValidation();}
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST" }))
{
<table style="margin: 0px auto;">
<tr>
<td>
#Html.LabelFor(m => m.ServerName, new { #class = "label" })
</td>
<td>
#Html.TextBoxFor(m => m.ServerName, new { #class = "text" })
</td>
</tr>
<tr>
<td align='right'>
#Html.LabelFor(m => m.UserName, new { #class = "label" })
</td>
<td>
#Html.TextBoxFor(m => m.UserName, new { #class = "text" })
</td>
</tr>
<tr>
<td align='right'>
#Html.LabelFor(m => m.Password, new { #class = "label" })
</td>
<td>
#Html.PasswordFor(m => m.Password, new { #class = "text" })
</td>
</tr>
<tr>
<td align="right" colspan="2">
<div id='errorShade' class='shade'>
<div id='errorBox'>Password or Username is incorrect. Please try again.</div>
</div>
</td>
</tr>
<tr>
<td align="right" colspan="2">
<div id='loginShade' class='shade'>
<input type='submit' class='button' id='btn' value='Login' /></div>
</td>
</tr>
</table>
<div id='ajaxUpdate' style='position: absolute; visibility: hidden;'>
#{if (ViewBag.Failed != null && ViewBag.Failed)
{
<script type="text/javascript">
pulseState.stopPluse = true;
hideShowLogin(true, 'errorShade', 20);
hideShowLogin(false, 'loginShade', 33);
</script>
}}
</div>
}
</div>
</div>
<br />
<div id="copywrite">
#{ Html.RenderPartial("Copyright"); }
</div>
First things first you don't need the following line:
#{Html.EnableClientValidation();}
Simply enable client validation in your web.config (should be by default):
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="ClientValidationEnabled" value="true"/>
</appSettings>
Then make sure that you have included the following script into your page:
jquery-1.5.1.js
jquery.validate.js
jquery.validate.unobtrusive.js
jquery.unobtrusive-ajax.js (this is for all the Ajax.* helpers to work, it has nothing to do with validation)
As far as the whole page reloading is concerned, when you specify an UpdateTargetId element in the AJAX options, this element is updated with the results of the AJAX request returned by the server (often a partial).

MVC form doesn't validate

I am very new to MVC 3.
I am using custom helpers for the controls but when i submit the form, the control is not being validated.
Can some one tell me if i am missing something? Following is the code snippet.
public static MvcHtmlString TextBox(string fieldName)
{
TagBuilder tagBuilder = new TagBuilder("Input");
tagBuilder.MergeAttribute("type", "Text");
tagBuilder.AddCssClass("text-box");
tagbuilder.MergeAttribute("data-val","true");
tagbuilder.MergeAttribute("data-val-regex-pattern","true");
tagbuilder.MergeAttribute("data-val","true");
TagBuilder validator = new TagBuilder("span");
validator.MergeAttribute("data-valmsg-for", fieldName);
validator.MergeAttribute("data-valmsg-replace", "true");
validator.MergeAttribute("class", "field-validation-valid");
return new MvcHtmlString(string.Concat(tagBuilder.ToString(), validator.ToString()));
}
The view has the following code
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="main-border" style="width: 890px;">
<div style="clear: both;">
</div>
<div style="padding: 0px 20px 0px 20px;">
<table style="width: 100%">
<tr>
<td colspan="2" class="main-subhead2">
<div class="label-text">
</div>
</td>
</tr>
<tr>
<td>Email :</td>
<td>#ControlHelper.TextBox("txtEmailAddress")</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" onclick="return validate(this.form);" /></td>
</tr>
</table>
</div>
</div>
}
the source code of rendered by the page is :
<form action="/" method="post">
<div class="main-border" style="width: 890px;">
<div style="clear: both;">
</div>
<div style="padding: 0px 20px 0px 20px;">
<table style="width: 100%">
<tr>
<td colspan="2" class="main-subhead2">
<div class="label-text">
</div>
</td>
</tr>
<tr>
<td>Email :</td>
<td><Input class="text-box" data-val="True" data-val-regex-pattern="^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z]))*#[A-Za-z0-9_\.-]+[A-Za-z0-9_][A-Za-z0-9_]$" name="txtEmailAddress" type="Text" visible="True"></Input><span class="field-validation-valid" data-valmsg-for="txtEmailAddress" data-valmsg-replace="true"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" /></td>
</tr>
</table>
</div>
</div>
</form>
Input should be lowercased:
TagBuilder tagBuilder = new TagBuilder("input");
And don't forget to include the unobtrusive client side validation scripts to your page:
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
and ensure that client side validation is enabled in web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
There are a number of reasons your form may not validating. In MVC3, you're most likely going to want to use unobtrusive validation (via jQuery). You can learn how to do this (it's not a big change - just include the correct JavaScript libraries and update web.config) at Microsoft's ASP.NET website.
You may need to add (data-val-regex) attribute:
public static MvcHtmlString TextBox(string fieldName)
{
TagBuilder tagBuilder = new TagBuilder("Input");
tagBuilder.MergeAttribute("type", "Text");
tagBuilder.AddCssClass("text-box");
tagbuilder.MergeAttribute("data-val","true");
tagbuilder.MergeAttribute("data-val-regex-pattern","true");
tagbuilder.MergeAttribute("data-val","true");
tagbuilder.MergeAttribute("data-val-regex","Field must be character (?![ء|ئ|ؤ])[ء-يA-Za-z]");
TagBuilder validator = new TagBuilder("span");
validator.MergeAttribute("data-valmsg-for", fieldName);
validator.MergeAttribute("data-valmsg-replace", "true");
validator.MergeAttribute("class", "This is an invalid Email format!");
return new MvcHtmlString(string.Concat(tagBuilder.ToString(), validator.ToString()));
}

Resources