How to validate visible controls alone in bootstrap - c#

I'm using bootstrap in my application.
I'm creating tabs, dropdown and textbox controls dynamically based on a count and applying validation to those controls.But it is validation all the controls. I need validation for visible controls , it should validate hidden controls.
Here is my code:
CategoryClass.cs
public class CategoryClass
{
public int ddlCount{ get; set; }
public int txtCount{ get; set; }
public int Id{ get; set; }
public string Name{ get; set; }
}
Default.aspx.cs
public partial class DefaultClass
{
public int CategoryCount{ get; set; }
public List<CategoryClass> CategoryList;
protected void Page_Load(object sender, EventArgs e)
{
CategoryList=new DefaultManager().GetCategoryList();
}
}
Default.aspx
<div class="row-fluid">
<div class="tabbable tabs-left">
<div id="rsc-fuelux-wizard" class="span3" style="border: 1px solid #C5D0DC; margin-right: 5px;">
<table>
<tr>
<td>
<div class="infobox infobox-light-brown infobox-dark span12" style="background-color: #B3BCC4;">
<h5 class="span12 center">
Category List</h5>
</div>
</td>
</tr>
<tr>
<td>
<ul class="nav nav-pills nav-stacked" id="CategoryTabs" style="margin-left: 5px;
margin-right: 5px;">
<%
int counter = 0;
foreach (CategoryClass Category in CategoryList)
{
counter++;
%><li stepval="<%=counter %>" id="Categoryli_<%=counter %>" <%
if (counter == 1)
{%> class="complete active" <%}
else
{%> class="complete" <%
}
%> cat-id="<%=Category.Id%>"><a href="javascript:void(0);" data-toggle="pill" onclick="ShowDiv(<%=Category.Id%>,<%=counter %>);">
<%=counter %>. <%=Category.Name%></a></li>
<%}
%>
</ul>
</td>
</tr>
</table>
<div class="tab-content">
<%counter = 0;
foreach (CategoryClass Category in CategoryList)
{
<div visibility="cat-list" id="Div_<%=Category.Id%>" style="height: 380px;"
class=" <%
if (counter == 1)
{%>tab-pane active <%
}
else
{%>tab-pane<%
}
%>">
<div class="form-horizontal">
<%if (Category.ddlCount> 0)
{
for(int i=0;i<Category.ddlCount;i++)
{%>
<div class="control-group">
<label class="control-label">DropDown <%=i++%>
</label>
<div class="controls">
<select data-val="true" data-val-required="Field is required" name="">
<option value="">--Select--</option>
<option value=1>Value1</option>
<option value=2>Value2</option>
</select>
</div>
</div>
<%
}
}
if (Category.txtCount> 0)
{
for(int i=0;i<Category.txtCount;i++)
{%>
<div class="control-group">
<label class="control-label">Textbox<%=i++%>
</label>
<div class="controls">
<input type="text" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>
</div>
</div>
<%}
}%>
</div>
</div>
</div>
</div>
<button id="btnSubmit" class="btn btn-success" onclick="Submit();">
Submit</button>
<script type="text/javascript">
$(document).ready(function () {
ConfigureValidator();
});
function ConfigureValidator() {
var basicDetailValidator = $('#Form1').data('validator');
var checkatleastOneCheckboxes = $("input[type='checkbox'][data-val-checkatleastone]");
checkatleastOneCheckboxes.each(function () {
var nameAttr = this.name;
basicDetailValidator.settings.rules[nameAttr].required = true;
basicDetailValidator.settings.messages[nameAttr].required = $(this).attr("data-val-checkatleastone");
});
basicDetailValidator.settings.errorElement = 'span';
basicDetailValidator.settings.errorClass = 'help-inline';
basicDetailValidator.settings.highlight = function (e) {
$(e).closest('.control-group').removeClass('info').addClass('error');
}
basicDetailValidator.settings.success = function (e) {
$(e).closest('.control-group').removeClass('error').addClass('info');
$(e).remove();
}
basicDetailValidator.settings.errorPlacement = function (error, element) {
if (element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('.controls');
if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
} else if (element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
} else {
error.insertAfter(element);
}
};
}
function Submit() {
if (!$('#Form1').valid()) {
return false;
}
}
function ShowDiv(objCatId, objCounter) {
$('ul.CategoryTabs li').attr('class', 'complete');
$('#Categoryli_' + objCounter).attr('class', 'complete active');
$('div[visibility="cat-list"]').css('display', 'none');
$('#Div_' + objCatId).css('display', 'block');
}
</script>
I'm using js/jquery.validate.min.js , js/uncompressed/jquery.validate.js and js/uncompressed/jquery.validate.unobtrusive.js .
Validation should be applied for visible controls alone.
Please help me out.

Basically you have to just call ASP.NET inbuilt JS function " ValidatorEnable" after the disable method call
Enable/disable asp.net validator controls within a specific "ValidationGroup" with jQuery?
http://geekswithblogs.net/jonasb/archive/2006/08/11/87708.aspx
Disable Validation on Hidden Controls

Related

Search with multiple fields in asp.net core mvc

I create form where I get data from database using sql queries in asp.net core mvc. Now I want to search data with multiple fields like price, area, areaUnit . I am new to c# Kindly help me to search data and display. Data display in other div. In that div I make cards and get data from database using foreachloop.
MY view :
#model IEnumerable<eHouse.Models.RentModel>
<form>
<div class="wrap">
<div class="search">
<input type="text" class="searchTerm" style="width: 700px; color:#000000; text-align: left;" placeholder="Search Houses" onclick="filterfunction()">
<button type="submit" class="searchButton" >
<i class="fa fa-search"></i>
</button>
</div>
<div id="filter">
<select>
<option value="Kanal">Kanal</option>
<option value="Marla">Marla</option>
<option value="Square Feet">Square Feet</option>
<option value="Square Meter">Square Meter</option>
<option value="Square Yards">Square Yards</option>
</select>
<input type="text" placeholder="area" />
<input type="text" placeholder="price" />
</div>
</div>
</form>
<div class="property_information" >
#foreach (var item in Model)
{
<div class="home-info">
<span id="houseid">
</span>
<a href="#" class="home-images">
<img src="#item.pic1" />
</a>
<div class="home-data">
<div class="home-name">
<p>#item.tittle</p>
</div>
<div class="price">
<p>#item.price</p>
</div>
<div class="features">
<span>
#item.bedroom
</span>
<span>
#item.bathroom
</span>
<span>
2
</span>
</div>
<div class="desc">
#item.descrip
</div>
<div class="contact-save">
<a href="#" class="phone_number" id="favorite" onclick="Fav(this)" data-id="#item.id" >
<i class="fas fa-heart" style=" color: white;"></i>
</a>
<div class="popup" onclick="myFunction()">
<a href="tel:+928754756478" class="phone_number" onclick="call()">
</a>
</div>
<div class="popupmsg" onclick="myFunctionmsg()">
<a href="#" class="phone_number open_message" onclick="msg()">
</a>
</div>
<a href="#" class="phone_number" onclick="del(this)" data-id="#item.id">
<i class="fas fa-trash-alt" style=" color: white;"></i>
</a>
</div>
</div>
</div>
}
</div>
My Controller:
public IActionResult Rent(int PageNumber = 1)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(6);
ViewBag.Totalpages = Math.Ceiling(data.Count()/6.0);
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
return View(data);
}
Pass the filter data through a input submit in the form. You will need new viewModel with your data, input for post and filterList
You need something like this,
#model YourViewModel;
//Your form
<label asp-for="Input.Name"></label>
<select asp-for="Input.Name" asp-items="#(new SelectList(Model.SearchList))" class="form-control">
<option></option>
</select>
<span asp-validation-for="Input.Name" class="text-danger"></span>
<input type="submit" value="Search" class="btn btn-primary"/>
//your loop
#foreach (var item in Model.Data)
//Contoller
public IActionResult Rent(int PageNumber = 1, InputModel input)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(6);
ViewBag.Totalpages = Math.Ceiling(data.Count()/6.0);
if(!string.InNullOrEmpty(input.Name))
{
data = data.Where(x => x.Name == input.Name).ToList();
}
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
var viewModel = new YourViewModel
{
Data = data // data,
SearchList = your List<string>(), //for dropdown
Input = new YourInputModel(),
}
return View(viewModel);
}
//Input model
public class YourInputModel
{
public string Name { get; set; }
}
//View model
public class YourViewModel
{
public YourDataType Data{ get; set; }
public List<strings> SearchList { get; set; }
public YourInputModel Input { get; set; }
}
You also need some other things, which I hope you will handle

Refresh partial view using jquery

This partial view is used to list cart-items:
<ul class="cart-dropdown">
<li>
<div class="cart-items cart-caption">
<ul>
#foreach (var i in Model.CartItems)
{
<li id="list-item-#i.item.ItemID">
<div class="container-fluid item-wrap" style="position: relative">
<div class="item-remove">
<a href="#" class="RemoveLink"
data-id="#i.RecordID" data-itemid="#i.item.ItemID">
x
</a>
</div>
<div class="col-md-2 item-img">
<div class="row-cart">
<img alt="" id="cartImg" height="71" width="75" src="#i.item.ImageUrl">
</div>
</div>
<div class="col-md-5 item-info">
<div class="row-cart">
<div class="brand-name">
<a href="#" class="brandName">
#i.item.BrandName
</a>
</div>
<div class="product-name">
<a href="#" class="productName">
#i.item.ItemName
</a>
</div>
<div class="product-qty">
<p class="productQTY" id="item-count-#i.item.ItemID">
#i.Count x #i.item.ItemPrice
</p>
</div>
</div>
</div>
<div class="col-md-5 price-info">
<div class="row-cart" style="margin-top: 10px">
<div class="col-md-6">
<div class="row-mrp">
<span class="cartItemPrice" id="item-total-#i.item.ItemID">
Rs #(#i.Count * #i.item.ItemPrice)
</span>
</div>
</div>
</div>
</div>
</div>
</li>
}
</ul>
</div>
</li>
<li class="clearfix">
<div class="col-md-6">
<div class="row-cart sub-cost" style="background: #fff; margin-left: -10px; margin-right: 0">
<p>
Sub Total :
<span style="float: right">
Rs
<span class="ng-binding"></span>
</span>
</p>
<p>
Delivery Charge :
<span qa="delChargeMB" style="float: right">Free</span>
</p>
</div>
<div class="row-cart cart-chkout-btn">
<button type="button">View Basket & Checkout</button>
</div>
</div>
</li>
</ul>
Above partial view is rendered when user clicks on "My cart" button. I need to allow customers to remove any cart-item they like by clicking a 'remove' button inside _cartDetails.cshtml. This jQuery code is being used to accomplish this task:
$(function () {
$(".RemoveLink").click(function () {
var recordToDelete = $(this).attr("data-id");
var itemID = $(this).attr("data-itemid");
if (recordToDelete != '') {
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete, "itemID": itemID },
function (data) {
if (data.ItemCount == 0) {
$('#list-item-' + recordToDelete).fadeOut('slow');
}
else {
$('#item-count-' + recordToDelete).text(data.ItemCount + " x " + data.ItemPrice);
$('#item-total-' + recordToDelete).text(data.ItemCount * data.ItemPrice);
}
$('#update-message').text(data.Message);
$(".confirmItemCart").show();
$(".confirmItemCart").addClass("collapsed");
$('.confirmItemCart').delay(30000).fadeOut('slow');
$('#cart-status').text('Cart (' + data.CartCount + ')');
$('#cart-total').text(data.CartTotal);
});
}
})
});
Controller: (UPDATED)
public ActionResult cartDropDown()
{
return RedirectToAction("cartDropDownChild");
}
[ChildActionOnly]
public ActionResult cartDropDownChild()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up list of cart items with total value
var viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal(),
ItemCount = cart.GetCount(),
Message = Server.HtmlEncode("There are no items in your cart. Continue shopping.")
};
foreach (var item in viewModel.CartItems)
{
item.item = db.Items.Single(i => i.ItemID == item.ItemID);
}
return PartialView("_cartDetails", viewModel);
}
This code is successfully removing items from the cart-items list but not updating the partial view (_cartDetails.cshtml). In debug mode, I've checked the values for the (data) which is returned from the ajax call and all values are correct. It is just the binding of those values with the _cartDetails html elements that is not working. Maybe I'm missing out something. Someone please guide.
Thanks in advance.
This is actually a system design related issues. Partial view gets rendered when the page loads.
When you are removing an item why don't you post to a child action which would render the same partial view and return the html. Then you can put the html in place. You do not need to handle the list-item, cart-total, cart-status etc. manually.
Add the [ChildActionOnly] filter to the action that renders the cart information section.
Then in the action: return PartialView("_cartDetails");
For example:
Move the logic from cartDropDown() function to a private function which will return a viewModel object. Then call that private function from both cartDropDown() and also in RemoveFromCart action (after deleting the data).
[ChildActionOnly]
public ActionResult cartDropDown()
{
return PartialView("_cartDetails", preparecartDropDown(this.HttpContext));
}
[ChildActionOnly]
public ActionResult RemoveFromCart(...)
{
//Delete data
return PartialView("_cartDetails", preparecartDropDown(this.HttpContext));
}
private ShoppingCartViewModel preparecartDropDown(HttpContext context)
{
var cart = ShoppingCart.GetCart(context);
var viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal(),
ItemCount = cart.GetCount(),
Message = Server.HtmlEncode("There are no items in your cart. Continue shopping.")
};
foreach (var item in viewModel.CartItems)
{
item.item = db.Items.Single(i => i.ItemID == item.ItemID);
}
return viewModel;
}

I tried to render partial view inside my view with jquery , but the the part of partial view dosen't appear in run time

these are the actions in controller:
public ActionResult AdminRoles(int? selectedValue)
{
if (!LogedUser.InRole(Functions.User, Roles.View)) return RedirectToAction("Login");
return View(db.Users.Where(u => u.Id != 1));
}
[HttpGet]
public ActionResult GetAdminRoles(int Id)
{
var secRole = db.SecurityRoles.Where(s => s.AdminId == Id);
var func = db.SystemFunctions.ToList();
if (func.Count() > secRole.Count())
{
foreach (var item in func)
{
if (secRole.Where(s => s.SystemFunctionId == item.Id).Count() <= 0)
{
SecurityRoles sec = new SecurityRoles();
sec.AdminId = Id; sec.SystemFunctionId = item.Id;
sec.CanView = false; sec.CanAdd = false; sec.CanEdit = false; sec.CanDelete = false;
db.SecurityRoles.Add(sec);
db.SaveChanges();
}
}
}
return PartialView("GetAdminRoles",db.SecurityRoles.Where(s => s.AdminId == Id));
}
[HttpPost]
public ActionResult GetAdminRoles(int hdnAdminIDs, int[] CanView, int[] CanAdd, int[] CanEdit, int[] CanDelete)
{
var list = db.SecurityRoles.Where(o => o.AdminId == hdnAdminIDs).ToList();
foreach (var item in list)
{
if (CanView != null && CanView.Contains(item.Id))
item.CanView = true;
else
item.CanView = false;
if (CanAdd != null && CanAdd.Contains(item.Id))
item.CanAdd = true;
else
item.CanAdd = false;
if (CanEdit != null && CanEdit.Contains(item.Id))
item.CanEdit = true;
else
item.CanEdit = false;
if (CanDelete != null && CanDelete.Contains(item.Id))
item.CanDelete = true;
else
item.CanDelete = false;
}
db.SaveChanges();
return RedirectToAction("AdminRoles");
}
the following is the AdminRoles() action which include the JQuery scripts that would bring the partial view GetAdminRoles
NOTE : I tried several scripts ( between the comment marks)
#model IEnumerable<Arabawy.Models.User>
#{
ViewBag.Title = "ContactusMessages";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
ViewBag.CurrentURI = "/IWS/adminroles".ToLower();
}
<script>
$(function () {
#*$.get('#Url.Content("~/IWS/GetAdminRoles/")' + "?Id=" + $('#AdminIDs').val(), function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});*#
$('#AdminIDs').change(function () {
debugger
/* Get the selected value of dropdownlist */
var selectedID = $(this).val();
/* Request the partial view with .get request. */
$.get('#Url.Content("~/IWS/GetAdminRoles/")' + "?Id=" + selectedID, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
</script>
<div class="pages_inner_content">
<div class="title_page_start">
<div class="right_title">
<h2>صلاحيات المشرفين</h2>
<h2><span>تحديث صلاحيات المشرفين</span></h2>
</div>
<div class="left_lisks">
<ul class="links_buttons">
#{if (Arabawy.LogedUser.IsLoged() &&
Arabawy.LogedUser.InRole(Arabawy.Controllers.IWSController.Functions.User, Arabawy.Roles.Edit))
{
<li class="add_fo">
<span> حفظ </span>
</li>
}}
<li class="exit">
خروج
</li>
</ul>
</div>
</div><!--title_page_start-->
<div class="bread_cramb bread_cramb_akh_ed">
<h3> أدوات الأداره <span> صلاحيات المشرفين </span> </h3>
</div> <!--bread_cramb-->
<div class="block_in_editor">
<h3>صلاحيات المشرفين</h3>
<div style="clear:both"></div>
<div class="add_khaber_form">
#Html.ValidationSummary(false)
<hr />
<div class="blog_form_input">
<label>اختر : </label>
<select class="select" id="AdminIDs" name="AdminIDs">
<option value="" selected>< اختر المشرف ></option>
#{foreach (var item in Model)
{
<option value="#item.Id">#item.DisplayName</option>
}}
</select>
</div>
<br />
<div id="partialPlaceHolder" style="display:none;"> </div>
</div><!--add_khaber_form-->
</div><!--block_in_editor-->
</div><!--pages_inner_content-->
this is the view of GetAdminRoles
#model IEnumerable<Arabawy.Models.SecurityRoles>
<script>
function submitForm() {
$("#hdnAdminIDs").val($("#AdminIDs").val());
$('#formID').attr('target', '_self');
$("#formID").submit();
}
</script>
<form action="#Url.Action("GetAdminRoles")" target="_self" id="formID" method="post" enctype="multipart/form-data">
#Html.Hidden("hdnAdminIDs")
<div class="block_in_adv">
<div style="clear:both"></div>
<div style="clear:both"></div>
<div class="table_adv_show">
<div class="row_first color_row">
<div class="cols_mos_2">اسم الصفحة</div>
<div class="cols_mos_3">امكانية رؤية الصفحة</div>
<div class="cols_mos_3">امكانية الأضافة </div>
<div class="cols_mos_3">امكانية التعديل </div>
<div class="cols_mos_3">امكانية المسح</div>
</div><!--main_row_opi-->
<ul class="list_pages_web sortable list" id="itemContainer">
#Html.Hidden("DeletedID")
#foreach (var item in Model)
{
<li class="zoomInUp">
<div class="block_row_table">
<div class="main_row_opi_res ">
<div class="cols_mos_2">اسم الصفحة</div>
<div class="cols_mos_3">امكانية رؤية الصفحة</div>
<div class="cols_mos_3">امكانية الأضافة </div>
<div class="cols_mos_3">امكانية التعديل </div>
<div class="cols_mos_3">امكانية المسح</div>
</div><!--main_row_opi-->
<div class="main_row_opi">
<div class="cols_mos_2">#item.SystemFunction.PageName</div>
#{
string canView = item.CanView ? "checked" : "";
string CanEdit = item.CanEdit ? "checked" : "";
string CanAdd = item.CanAdd ? "checked" : "";
string CanDelete = item.CanDelete ? "checked" : "";
}
<div class="cols_mos_3">
<input type="checkbox" name="CanView" id=#string.Format("CanView" + item.Id) class="css-checkbox9 all_check" value="#item.Id" #canView /><label for=#string.Format("CanView" + item.Id) class="css-label9" checked="checked"> </label>
</div>
<div class="cols_mos_3">
<input type="checkbox" name="CanAdd" id=#string.Format("CanAdd" + item.Id) class="css-checkbox9 all_check" value="#item.Id" #CanAdd /><label for=#string.Format("CanAdd" + item.Id) class="css-label9" checked="checked"> </label>
</div>
<div class="cols_mos_3">
<input type="checkbox" name="CanEdit" id=#string.Format("CanEdit" + item.Id) class="css-checkbox9 all_check" value="#item.Id" #CanEdit /><label for=#string.Format("CanEdit" + item.Id) class="css-label9" checked="checked"> </label>
</div>
<div class="cols_mos_3">
<input type="checkbox" name="CanDelete" id=#string.Format("CanDelete" + item.Id) class="css-checkbox9 all_check" value="#item.Id" #CanDelete /><label for=#string.Format("CanDelete" + item.Id) class="css-label9" checked="checked"> </label>
</div>
</div><!--main_row_opi-->
</div><!--/*block_row_table*/-->
</li>
}
</ul>
<div class="holder"></div>
</div><!--table_adv_show-->
</div><!--block_in_adv-->
so , why my partial view does not appear in run time ???!!!!
Is there any thing wrong ???!!
please help me !!!!!!!!!!!!!!!!!!!!!
Navigate to that partial view using your browser to ascertain it is returning what you expect. Once you have made sure that is returning the expected HTML, then your code should work.

Validation issue in textbox controls

I'm using bootstrap in my application.
I'm creating dropdown and textbox controls dynamically based on a count and applying validation to those controls.But validation is not working for those textbox controls alone.
Here is my code:
Default.aspx.cs
public partial class DefaultClass
{
public int ddlCount{ get; set; }
public int txtCount{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
}
Default.aspx
<div class="form-horizontal">
<%if (ddlCount > 0)
{
for(int i=0;i<ddlCount ;i++)
{%>
<div class="control-group">
<label class="control-label">DropDown <%=i++%>
</label>
<div class="controls">
<select data-val="true" data-val-required="Field is required" name="">
<option value="">--Select--</option>
<option value=1>Value1</option>
<option value=2>Value2</option>
</select>
</div>
</div>
<%
}
}
if (txtCount> 0)
{
for(int i=0;i<txtCount;i++)
{%>
<div class="control-group">
<label class="control-label">Textbox<%=i++%>
</label>
<div class="controls">
<input type="text" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>
</div>
</div>
<%}
}%>
</div>
<button id="btnSubmit" class="btn btn-success" onclick="Submit();">
Submit</button>
<script type="text/javascript">
$(document).ready(function () {
ConfigureValidator();
});
function ConfigureValidator() {
var basicDetailValidator = $('#Form1').data('validator');
var checkatleastOneCheckboxes = $("input[type='checkbox'][data-val-checkatleastone]");
checkatleastOneCheckboxes.each(function () {
var nameAttr = this.name;
basicDetailValidator.settings.rules[nameAttr].required = true;
basicDetailValidator.settings.messages[nameAttr].required = $(this).attr("data-val-checkatleastone");
});
basicDetailValidator.settings.errorElement = 'span';
basicDetailValidator.settings.errorClass = 'help-inline';
basicDetailValidator.settings.highlight = function (e) {
$(e).closest('.control-group').removeClass('info').addClass('error');
}
basicDetailValidator.settings.success = function (e) {
$(e).closest('.control-group').removeClass('error').addClass('info');
$(e).remove();
}
basicDetailValidator.settings.errorPlacement = function (error, element) {
if (element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('.controls');
if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
} else if (element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
} else {
error.insertAfter(element);
}
};
}
function Submit() {
if (!$('#Form1').valid()) {
return false;
}
}
</script>
I'm using js/jquery.validate.min.js , js/uncompressed/jquery.validate.js and js/uncompressed/jquery.validate.unobtrusive.js .
Validation is not working for textbox controls alone.
Please help me out.
try by including name attribute may it work
<input type="text" name="text_box" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>

Partial View returning null model

Now I bet this is a problem that happens often, I just can't seem to find anything related to it, or notice myself what is wrong with it. The view provided at bottom always returns null on foreach line.
I'm making a simple currency list.
Model:
public class Currency
{
public int ID { get; set; }
public string Name { get; set; }
public string Sign { get; set; }
public float BuyValue { get; set; }
public float MidValue { get; set; }
public float SellValue { get; set; }
public string CurrencyIcon { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DateCreated { get; set; }
}
And it should be posted as partial view, on several different ways so to say. For example, partial view that will get all of them (for today), and partial view that will get random 6 (also for today).
I'm doing the first part now, all of them, for today.
Controller
public ActionResult FrontPagePartial()
{
DateTime today = DateTime.Now.Date; //i'm filtering it by date only
var currencies = db.Currencies.Where(c => c.DateCreated.Equals(today));
return View(currencies);
}
I've checked the filtering it's working correctly. So my view goes like this:
#model IEnumerable<CurrencyList.Models.Currency>
<div id="currencyList_Partial">
<div id="bg_currencyList_Partial">
<img src="#Url.Content("~/Content/Resources/img.png")" />
</div>
<div id="header_currencyList_Partial">
<div style="padding: 10px;">
<p style="font-size: 18px;">
Currency List<br />
<span class="header_currencyList_Partial_Day">FOR TODAY</span>
</p>
<p class="header_currencyList_Partial_Link" >
DETAILS >
</p>
</div>
<div id="table_currencyList">
#foreach (var item in Model)
{
<table>
<tr>
<td style="text-align: center;"><img src='#item.CurrencyIcon' title='#item.Sign' /><p style="font-size: small;">#Html.DisplayFor(modelItem => item.Name)</p><p>#Html.DisplayFor(modelItem => item.Sign)</p></td>
<td style="text-align: center;">#Html.DisplayFor(modelItem => item.BuyValue)</td>
<td style="text-align: center;">#Html.DisplayFor(modelItem => item.MidValue)</td>
<td style="text-align: center;">#Html.DisplayFor(modelItem => item.SellValue)</td>
</tr>
</table>
}
</div>
</div>
</div>
Parent view
#{
ViewBag.Title = "Currency List Home Page";
}
#section HeadSection{
<link rel="stylesheet" href="#Url.Content("~/Content/layerslider.css")" type="text/css" media="screen" />
<link rel="stylesheet" href="#Url.Content("~/Content/defaultskin/skin.css")" type="text/css" media="screen" />
<noscript>
<link rel="stylesheet" href="#Url.Content("~/Content/noscript.css")" type="text/css" media="screen" />
</noscript>
}
#section ScriptSection{
<script src="#Url.Content("~/Scripts/jqueryui.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/plugins.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/page.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/layerslider.kreaturamedia.jquery.js")" type="text/javascript"></script>
}
<div id="content">
<div id="statusbar"></div>
<div id="slider">
<div id="layerslider">
<div class="ls-layer" style="slidedelay: 3000">
<img class="ls-bg" src="#Url.Content("~/Content/images/slider_gallery/slide1_layer1.png")" alt="layer" />
<img class="ls-s2" src="#Url.Content("~/Content/images/slider_gallery/behind_text_layer.png")" alt="sublayer" style="durationin: 0; top: 247px;/*easingin: easeOutElastic*/" />
<img class="ls-s3" src="#Url.Content("~/Content/images/slider_gallery/text_layer1.png")" alt="sublayer" style="durationin: 2000; top: 255px;left: 15px; easingin: easeOutElastic " />
</div>
<div class="ls-layer" style="slidedelay: 3000">
<img class="ls-bg" src="#Url.Content("~/Content/images/slider_gallery/slide2_layer1.png")" alt="layer" />
<img class="ls-s2" src="#Url.Content("~/Content/images/slider_gallery/behind_text_layer.png")" alt="sublayer" style="durationin: 0; top: 247px;/*easingin: easeOutElastic*/" />
<img class="ls-s3" src="#Url.Content("~/Content/images/slider_gallery/text_layer1.png")" alt="sublayer" style="durationin: 2000; top: 255px;left: 15px;easingin: easeOutElastic " />
</div>
<div class="ls-layer" style="slidedelay: 3000">
<img class="ls-bg" src="#Url.Content("~/Content/images/slider_gallery/slide3_layer1.png")" alt="layer" />
<img class="ls-s2" src="#Url.Content("~/Content/images/slider_gallery/behind_text_layer.png")" alt="sublayer" style="durationin: 0;top: 247px;" />
<img class="ls-s3" src="#Url.Content("~/Content/images/slider_gallery/text_layer1.png")" alt="sublayer" style="durationin: 2000; top: 255px; left: 15px; easingin: easeOutElastic " />
</div>
</div>
</div>
<div id="converter">
<h2>CONVERTER</h2>
<p class="shadowedText">
VALUE:
</p>
<p>
<input type="text" id="tb11" class="tb11" />
</p>
<p class="shadowedText">
FROM CURRENCY
</p>
<div class="select1 select1p">
<select id="select1">
<option>EUR - EURO</option>
<option> $ - DOLLAR</option>
</select>
<span class="selectArrow"><img src="#Url.Content("~/Content/images/select_arrows.png")" /></span>
</div>
<p class="shadowedText">
TO CURRENCY
</p>
<div class="select1 select1p">
<select id="select2">
<option> $ - EURO</option>
<option> EURO - DOLLAR</option>
</select>
<span class="selectArrows"><img src="#Url.Content("~/Content/images/select_arrows.png")" /></span>
</div>
<div class="select1p addMargin">
<span class="boldResult">100 EUR = 11710.55 $</span><br />
<span class="lightResult">100 $ = 0.84882 EUR</span>
</div>
</div>
</div>
<div id="lowerContent">
<div id="blog"><img src="#Url.Content("~/Content/images/vesti.png")" /></div>
//This is where Partial View is rendered
<div id="listC">#Html.Partial("FrontPagePartial")</div>
</div>
<div id="portals">
</div>
<div id="listC">#Html.Partial("FrontPagePartial")</div>
This is trying to render the partial view, FrontPagePartial, with the model of the parent view, which is not defined.
public ActionResult FrontPagePartial()
This creates an action so you can go, siteurl/controller/FrontPagePartial
What you need to do is
<div id="listC">#Html.Partial("FrontPagePartial", currencies)</div>
If you don't mind ViewBag, you can set ViewBag.Currencies in the Action method and
<div id="listC">#Html.Partial("FrontPagePartial", ViewBag.Currencies)</div>
The #Html.Partial just renders the html partial directly from the file view (in the Shared folder, not through the FrontPagePartial method in the controller) using the model that the parent owns. In your case Razor try to use the Model from the parent view but apparently you never defined it. That's the reason for the null object
#foreach (var item in Model) { ... }
You want to call a partial view that returns another kind of object model; that's not possible with #Httml.Partial nor #Html.RenderPartial. Two solutions:
Ajax call:
$(document).ready(function() {
$.get('#Url.Action("FrontPagePartial")',null,function(data) {
$('#listC').html(data);
});
});
Using Html.RenderAction or Html.Action:
<div id="listC">#Html.RenderAction("FrontPagePartial")</div>
Don't forget to change the return in the FrontPagePartial method. Without this the result will be the list of currencies inside the layout page (you are returning a simple page, not a partial view):
public ActionResult FrontPagePartial()
{
....
return PartialView(currencies);
}

Categories

Resources