I need populate on MVC form View the TextBox below
#Html.LabelFor(m => m.tDate)
#Html.TextBoxFor(m => m.tDate, "{0:dd/MM/yyyy}", new { #class = "Mytextarea2" })
#Html.ValidationMessageFor(m => m.tDate, "", new { #class = "text-danger" })
Whit value extract from controller (using MySql database) when I have planned this code
public DateTime JsonDateTimeToNormal(string jsonDateTime)
{
jsonDateTime= #"""" + jsonDateTime + #"""";
return Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(jsonDateTime);
}
...
model.tDate = JsonDateTimeToNormal(GetDateHourById(value).ToString());
...
private static string GetDateHourById(string value)
{
string sql;
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
sql = #String.Format(" SELECT ");
sql += String.Format(" tDate ");
sql += String.Format(" FROM `dotable` ");
sql += String.Format(" WHERE tID = #Id;");
using (MySqlCommand cmd = new MySqlCommand(sql))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Id", value);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
return name;
}
}
}
The value memorized on MySql database is
2020-03-19
But the TextBox is populed with this value
/Date(1605481200000)/
On the model
[Column(TypeName = "date")]
[Display(Name = "Your date")]
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? tDate { get; set; }
Help me to do it.
Debug VS 2109
Solution
const d = new Date(response.tDate.match(/\d+/)[0] * 1);
const formattedDate = d.getFullYear()+'-'+("0"+(d.getMonth()+1)).slice(-2)+'-'+("0"+d.getDate()).slice(-2)
$('#tDate').val( formattedDate );
why don't you try to make this call with a jquery?
view:
#Html.TextBoxFor(m => m.tDate, "{0:dd/MM/yyyy}", new { #class = "Mytextarea2" })
$("#document").on("click", ".YouFormCall", function () {
var date = new Object();
date.tDate = $(this).closest('tr').find(".Mytextarea2").val();
controller:
yourModel date= new yourModel ()
{
tDate= date.tDate,
};
db.Entry(date).State = EntityState.Modified;
db.SaveChanges();
}
Related
I have the following enum:
public enum EventType : int
{
[Display(Description = "Downtime")]
Downtime = 0,
[Display(Description = "Speed")]
Speed = 1,
[Display(Description = "Quality")]
Quality = 2
}
I am creating a dropdown list for it using:
#Html.EnumDropDownListFor(m => m.Type, "Event Type", new { #class = "form-control" })
The options I get in the dropdown are:
Event Type
Downtime
Speed
Quality
Why on earth is Event Type an option? And what possible value could it represent??
The [Display] attributes are my feeble attempt at fixing this...
Any ideas?
At first you need to create a HTML Helper extension like:
public static class HtmlHelperExtensions
{
private static string GetDisplayName(this Enum enumeration)
{
var enumType = enumeration.GetType();
var enumName = Enum.GetName(enumType, enumeration);
var member = enumType.GetMember(enumName)[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var attribute = (DisplayAttribute)attributes[0];
var displayName = attribute.Name;
if (attribute.ResourceType != null)
{
displayName = attribute.GetName();
}
return displayName;
}
public static MvcHtmlString EnumDropDownFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, Func<TEnum, bool> predicate=null, string optionLabel=null, object htmlAttributes=null) where TEnum : struct, IConvertible
{
var enumList = predicate == null ? Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
: Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(e => predicate(e));
var selectList = enumList
.Select(e => new SelectListItem
{
Value = Convert.ToUInt64(e).ToString(),
Text = ((Enum)(object)e).GetDisplayName(),
}).ToList();
if (!string.IsNullOrEmpty(optionLabel))
{
selectList.Insert(0, new SelectListItem
{
Text = optionLabel
});
}
return htmlAttributes==null
? htmlHelper.DropDownListFor(expression, selectList)
: htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}
}
Then if your Enum like bellow
public enum EventType
{
[Display(Description = "Downtime")]
Downtime = 0,
[Display(Description = "Speed")]
Speed = 1,
[Display(Description = "Quality")]
Quality = 2
[Display(Description = "Test")]
Test = 3
}
and you are don't want to load Test then use:
#Html.EnumDropDownFor(model => model.Type, types => types != EventType.Test, "Event Type", new {#class = "form-control"})
Or if you need to load all then:
#Html.EnumDropDownFor(model => model.Type, optionLabel:"Event Type", htmlAttributes:new {#class = "form-control"})
i could do it server side part. i want if start date is not empty then end date must be equal or greater than start date. server side logic is almost complete but i am bit confuse what to do for client side logic. basically i want to do it by IClientValidatable interface.
my server side code as follows
Model code
public class DateValTest
{
[Display(Name = "Start Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[DateGreaterThanAttribute(otherPropertyName = "StartDate", ErrorMessage = "End date must be greater than start date")]
public DateTime? EndDate { get; set; }
}
attribute code
public class DateGreaterThanAttribute : ValidationAttribute
{
public string otherPropertyName;
public DateGreaterThanAttribute() { }
public DateGreaterThanAttribute(string otherPropertyName, string errorMessage)
: base(errorMessage)
{
this.otherPropertyName = otherPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
// Using reflection we can get a reference to the other date property, in this example the project start date
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.otherPropertyName);
var extensionValue = field.GetValue(validationContext.ObjectInstance, null);
var datatype = extensionValue.GetType();
//var otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(this.otherPropertyName);
if (field == null)
return new ValidationResult(String.Format("Unknown property: {0}.", otherPropertyName));
// Let's check that otherProperty is of type DateTime as we expect it to be
if ((field.PropertyType == typeof(DateTime) || (field.PropertyType.IsGenericType && field.PropertyType == typeof(Nullable<DateTime>))))
{
DateTime toValidate = (DateTime)value;
DateTime referenceProperty = (DateTime)field.GetValue(validationContext.ObjectInstance, null);
// if the end date is lower than the start date, than the validationResult will be set to false and return
// a properly formatted error message
if (toValidate.CompareTo(referenceProperty) < 1)
{
validationResult = new ValidationResult(ErrorMessageString);
}
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
// Do stuff, i.e. log the exception
// Let it go through the upper levels, something bad happened
throw ex;
}
return validationResult;
}
}
my concern is how to pass start date textbox name from server side to client side which will add some attribute to end date textbox.
so just help me to construct few server side code for GetClientValidationRules function and few code for client side unobtrusive code say for example $.validator.unobtrusive.adapters.add and $.validator.addMethod anyone can help me like how to achieve it. thanks
UPDATE
i try to solve it this way but my client side js is not triggering. here is my revised code.
Model code
public class DateValTest
{
[Display(Name = "Start Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[MyDate(ErrorMessage = "Back date entry not allowed")]
[DateGreaterThanAttribute(otherPropertyName = "StartDate", ErrorMessage = "End date must be greater than start date")]
public DateTime? EndDate { get; set; }
}
my attribute related code
public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable
{
public string otherPropertyName;
public DateGreaterThanAttribute() { }
public DateGreaterThanAttribute(string otherPropertyName, string errorMessage)
: base(errorMessage)
{
this.otherPropertyName = otherPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
// Using reflection we can get a reference to the other date property, in this example the project start date
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.otherPropertyName);
var extensionValue = field.GetValue(validationContext.ObjectInstance, null);
var datatype = extensionValue.GetType();
//var otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(this.otherPropertyName);
if (field == null)
return new ValidationResult(String.Format("Unknown property: {0}.", otherPropertyName));
// Let's check that otherProperty is of type DateTime as we expect it to be
if ((field.PropertyType == typeof(DateTime) || (field.PropertyType.IsGenericType && field.PropertyType == typeof(Nullable<DateTime>))))
{
DateTime toValidate = (DateTime)value;
DateTime referenceProperty = (DateTime)field.GetValue(validationContext.ObjectInstance, null);
// if the end date is lower than the start date, than the validationResult will be set to false and return
// a properly formatted error message
if (toValidate.CompareTo(referenceProperty) < 1)
{
validationResult = new ValidationResult(ErrorMessageString);
}
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
// Do stuff, i.e. log the exception
// Let it go through the upper levels, something bad happened
throw ex;
}
return validationResult;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "isgreater",
};
rule.ValidationParameters.Add("otherproperty", otherPropertyName);
yield return rule;
}
}
my js code
$.validator.unobtrusive.adapters.add('isgreater', ['otherproperty'], function (options) {
options.rules['isgreater'] = { isgreater: options.params.otherproperty };
options.messages['isgreater'] = options.message;
});
$.validator.addMethod("isgreater", function (value, element, param) {
alert('pop' + params.otherproperty);
var otherProp = $('#' + params.otherproperty);
var date = new Date(value);
if (otherProp.val() != '')
{
return date >= minDate;
}
return true;
});
My end date textbox html look like as following
<input type="date"
value="03/16/2016"
name="EndDate"
id="EndDate"
data-val-restrictbackdates-mindate="03/16/2016 00:00:00"
data-val-restrictbackdates="Back date entry not allowed"
data-val-isgreater-otherproperty="StartDate"
data-val-isgreater="End date must be greater than start date"
data-val-date="The field End Date must be a date."
data-val="true"
class="input-validation-error form-control text-box single-line">
the problem is my js code is not firing.....could not capture the area what is the mistake in js code. need some hint or help. thanks
I solve it...Updated code here
Model code
public class DateValTest
{
[Display(Name = "Start Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[MyDate(ErrorMessage = "Back date entry not allowed")]
[DateGreaterThanAttribute(otherPropertyName = "StartDate", ErrorMessage = "End date must be greater than start date")]
public DateTime? EndDate { get; set; }
}
Custom attribute related class code
public class MyDateAttribute : ValidationAttribute, IClientValidatable
{
private DateTime _MinDate;
public MyDateAttribute()
{
_MinDate = DateTime.Today;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime _EndDat = DateTime.Parse(value.ToString(), CultureInfo.InvariantCulture);
DateTime _CurDate = DateTime.Today;
int cmp = _EndDat.CompareTo(_CurDate);
if (cmp > 0)
{
// date1 is greater means date1 is comes after date2
return ValidationResult.Success;
}
else if (cmp < 0)
{
// date2 is greater means date1 is comes after date1
return new ValidationResult(ErrorMessage);
}
else
{
// date1 is same as date2
return ValidationResult.Success;
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "restrictbackdates",
};
rule.ValidationParameters.Add("mindate", _MinDate);
yield return rule;
}
}
public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable
{
public string otherPropertyName;
public DateGreaterThanAttribute() { }
public DateGreaterThanAttribute(string otherPropertyName, string errorMessage)
: base(errorMessage)
{
this.otherPropertyName = otherPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
// Using reflection we can get a reference to the other date property, in this example the project start date
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.otherPropertyName);
var extensionValue = field.GetValue(validationContext.ObjectInstance, null);
if(extensionValue==null)
{
//validationResult = new ValidationResult("Start Date is empty");
return validationResult;
}
var datatype = extensionValue.GetType();
//var otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(this.otherPropertyName);
if (field == null)
return new ValidationResult(String.Format("Unknown property: {0}.", otherPropertyName));
// Let's check that otherProperty is of type DateTime as we expect it to be
if ((field.PropertyType == typeof(DateTime) || (field.PropertyType.IsGenericType && field.PropertyType == typeof(Nullable<DateTime>))))
{
DateTime toValidate = (DateTime)value;
DateTime referenceProperty = (DateTime)field.GetValue(validationContext.ObjectInstance, null);
// if the end date is lower than the start date, than the validationResult will be set to false and return
// a properly formatted error message
if (toValidate.CompareTo(referenceProperty) < 1)
{
validationResult = new ValidationResult(ErrorMessageString);
}
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
// Do stuff, i.e. log the exception
// Let it go through the upper levels, something bad happened
throw ex;
}
return validationResult;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "isgreater",
};
rule.ValidationParameters.Add("otherproperty", otherPropertyName);
yield return rule;
}
}
View code with js
#model AuthTest.Models.DateValTest
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DateValTest</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="https://cdn.jsdelivr.net/momentjs/2.12.0/moment.min.js"></script>
<script type="text/javascript">
$.validator.unobtrusive.adapters.add('restrictbackdates', ['mindate'], function (options) {
options.rules['restrictbackdates'] = { mindate: options.params.mindate };
options.messages['restrictbackdates'] = options.message;
});
$.validator.addMethod("restrictbackdates", function (value, element, param) {
var date = new Date(value);
var minDate = new Date(param.mindate);
return date >= minDate;
});
$.validator.unobtrusive.adapters.add('isgreater', ['otherproperty'], function (options) {
options.rules['isgreater'] = { otherproperty: options.params.otherproperty };
options.messages['isgreater'] = options.message;
});
$.validator.addMethod("isgreater", function (value, element, param) {
var otherProp = $('#' + param.otherproperty);
if (otherProp.val() != '') {
var StartDate = new Date(moment(otherProp.val(), 'MM/DD/YYYY'));
var Enddate = new Date(value);
if (StartDate != '') {
return Enddate >= StartDate;
}
}
return true;
});
</script>
}
If I am getting it right - then you need to add validation on End Date based on Start Date i.e., Depending value.
It can be done very easily using Foolproof.js where there are various attributes like RequiredIf, RequiredIfRegexMatch etc. You can also write you customized code overridding the default attributes in the same manner like we do for MVC attributes.
One example:
using Foolproof;
public class MustBeTrueIfAttribute : RequiredIfAttribute
{
static MustBeTrueIfAttribute()
{
Register.Attribute(typeof(MustBeTrueIfAttribute));
}
public MustBeTrueIfAttribute(string dependentProperty, object dependentValue)
: base(dependentProperty, dependentValue)
{
}
public MustBeTrueIfAttribute(string dependentProperty, Operator #operator, object dependentValue)
: base(dependentProperty, #operator, dependentValue)
{
}
public override string ClientTypeName => "mustbetrueif";
public override bool IsValid(object value, object dependentValue, object container)
{
return !this.Metadata.IsValid(dependentValue, this.DependentValue) || (value != null && (bool)value);
}
}
for client side validation , if you are using jquery ui (datepicker) all you need to do is
$(function () {
$("#txtFrom").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() + 1);
$("#txtTo").datepicker("option", "minDate", dt);
}
});
$("#txtTo").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() - 1);
$("#txtFrom").datepicker("option", "maxDate", dt);
}
});
});
Source :http://www.aspsnippets.com/Articles/jQuery-DatePicker-Start-Date-should-be-less-than-End-date-validation.aspx
I wish to replace the hard coded data with SQL Server Database.
However, I'm stucked as I am still new to this.. I just tried the Google Chart and its working with hard-coded values, please guide me step-by-step to change the values to data from my database.
If theres any informations you need, please let me know. I'll try to provide them. Thanks for the help in advance guys! ):
Code for my Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ChartInMvcApplication.Models
{
public class ProductModel
{
public string YearTitle { get; set; }
public string SaleTitle { get; set; }
public string PurchaseTitle { get; set; }
public Product ProductData { get; set; }
}
public class Product
{
public string Year { get; set; }
public string Purchase { get; set; }
public string Sale { get; set; }
}
}
Code for my Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChartInMvcApplication.Models;
namespace ChartInMvcApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ProductModel objProductModel = new ProductModel();
objProductModel.ProductData = new Product();
objProductModel.ProductData = GetChartData();
objProductModel.YearTitle = "Year";
objProductModel.SaleTitle = "Sale";
objProductModel.PurchaseTitle = "Purchase";
return View(objProductModel);
}
/// <summary>
/// Code to get the data which we will pass to chart
/// </summary>
/// <returns></returns>
public Product GetChartData()
{
Product objproduct = new Product();
/*Get the data from databse and prepare the chart record data in string form.*/
objproduct.Year = "2009,2010,2011,2012,2013,2014";
objproduct.Sale = "2000,1000,3000,1500,2300,500";
objproduct.Purchase = "2100,1400,2900,2400,2300,1500";
return objproduct;
}
}
}
Code for my View:
#model ChartInMvcApplication.Models.ProductModel
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create and populate the data table.
var years = [#Model.ProductData.Year];
var sales = [#Model.ProductData.Sale];
var Purchase = [#Model.ProductData.Purchase];
var data = new google.visualization.DataTable();
data.addColumn('string', '#Model.YearTitle');
data.addColumn('number', '#Model.SaleTitle');
data.addColumn('number', '#Model.PurchaseTitle');
for (i = 0; i < years.length; i++) {
data.addRow([years[i].toString(), sales[i], Purchase[i]]);
}
var options = {
title: 'Sale and Purchase Compare',
hAxis: { title: '#Model.YearTitle', titleTextStyle: { color: 'red'} }
};
var chart = newgoogle.visualization.ColumnChart(document.getElementById('chartdiv'));
chart.draw(data, options);
}
</script>
<div id="chartdiv" style="width: 500px; height: 300px;">
</div>
You have to add data to each product object.
public Product GetChartData()
{
Product objproduct = new Product();
//Get Data for years as a string list.
List<string> years = Database.GetYears();
foreach(var year in years)
GetChartDataForYear(year, ref objproduct);
return objproduct;
}
public void GetChartDataForYear(string year, Product objproduct out)
{
if(!string.IsNullorEmpty(objproduct.Year))
objproduct.Year += (",");
if(!string.IsNullorEmpty(objproduct.Sale))
objproduct.Sale += (",");
if(!string.IsNullorEmpty(objproduct.Purchase ))
objproduct.Purchase += (",");
objproduct.Year += year.ToString();
objproduct.Sale += GetSale(int year);
objproduct.Purchase += GetPurchase(int year);
}
public string GetSale(string year)
{
// To get from DB.
return "";
}
public string GetPurchase(string year)
{
// To get from DB.
return "";
}
The best way is to bring the values from the database and bind them into a list, then do a foreach to populate your chart.
In your model create 3 functions like this :
public List<string> getYears()
{
List<string> years = new List<string>();
string connectionString = ConfigurationManager.AppSettings["StringConnection"].ToString();
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT year FROM tableTest", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
years.Add(reader["year"].ToString());
}
cn.Close();
}
return years;
}
public List<string> getSale()
{
List<string> sales = new List<string>();
List<string> years = getYears();
foreach (var year in years)
{
string connectionString = ConfigurationManager.AppSettings["StringConnection"].ToString();
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT sale FROM tableTest where year = '" + year + "'", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
sales.Add(reader["sale"].ToString());
}
cn.Close();
}
}
return sales;
}
public List<string> getPurchase()
{
List<string> purchases = new List<string>();
List<string> years = getYears();
foreach (var year in years)
{
string connectionString = ConfigurationManager.AppSettings["StringConnection"].ToString();
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT purchase FROM tableTest where year = '" + year + "'", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
purchases.Add(reader["purchase"].ToString());
}
cn.Close();
}
}
return purchases;
}
Add a function in your Model to change Lists to strings:
public string listToString(List<string> list)
{
string output = "";
foreach(var item in list)
{
output = (String.IsNullOrEmpty(output)) ? item : output + "," + item;
}
return output;
}
In your controller the function will be :
public Product GetChartData()
{
ProductModel prod = new ProductModel();
Product objproduct = new Product();
/*Get the data from databse and prepare the chart record data in string form.*/
objproduct.Year = prod.listToString(prod.getYears());
objproduct.Sale = prod.listToString(prod.getSale());
objproduct.Purchase = prod.listToString(prod.getPurchase());
return objproduct;
}
I filled Drop Down List in MVC which is working fine but now I want to do it using Dapper but got stuck.
DropDownList in MVC without Dapper
Controller
[HttpPost]
public ActionResult Create(User ur)
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
ModelState.Clear();
FillCountry();
}
public void FillCountry()
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "select * from tbl_country ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
while (rdr.Read())
{
li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
}
ViewData["country"] = li;
}
View
#{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new {onchange = "this.form.submit();" })
#{ Html.EndForm(); }
This is what I am trying to do now
DropDownList in MVC with Dapper
Model
public class Region
{
private int _CountryId;
private string _CountryName;
public int CountryId
{
get { return _CountryId; }
set { _CountryId = value; }
}
public string CountryName
{
get { return _CountryName; }
set { _CountryName = value; }
}
Controller
[HttpPost]
public ActionResult AddMobiles(TBMobileDetails MD, HttpPostedFileBase file)
{
FileUpload(file);
MobileMain MM = new MobileMain();
MM.AddMobiles(MD);
FillCountry();
return RedirectToAction("AllMobileList");
}
Stuck in this part how to fill it using dapper? How to populate my list?
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
}
View
#{ Html.BeginForm("AddMobiles", "AddMobile", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }
You are passing in ViewData["country"] object of type IEnumerable<Region> while in View you are casting it to IEnumerable<SelectListItem> which won't work obviously in action change FillCountry() to make SelectList:
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
var list = new SelectList(result,"CountryId","CountryName");
}
and in View now cast it to SelectList:
#Html.DropDownList("country", ViewData["country"] as SelectList, new {onchange = "this.form.submit();" })
This will get you going.
I have following code for Custom Ajax Binding. This has following problems even though it is displaying data for the first page.
• The request.Sorts is coming as NULL in to the Orders_Read method
• The request.PageSize is coming as 0 to the Orders_Read method
• The request.Page is coming as 1 to the Orders_Read method (even if I click on the page 2)
What changes need to be done here to get proper sort and pagesize values?
Note: I am using MVC Wrapper for Kendo Grid.
VIEW
#Scripts.Render("~/bundles/jquery")
<script type ="text/javascript">
$(document).ready(function (){
$('#Submit1').click(function () {
alert('1');
$('#grid12').data('kendoGrid').dataSource.read();
});
});
</script>
#model KendoPratapSampleMVCApp.Models.Sample
#{
ViewBag.Title = "CustomAjaxbind";
}
<h2>CustomAjaxbind</h2>
#using (Html.BeginForm("PostValues", "CustomAjaxBinding", FormMethod.Post))
{
<input id="Submit1" type="button" value="SubmitValue" />
#(Html.Kendo().Grid<KendoPratapSampleMVCApp.Models.Sample>()
.Name("grid12")
.EnableCustomBinding(true)
.Columns(columns => {
columns.Bound(p => p.SampleDescription).Filterable(false).Width(100);
columns.Bound(p => p.SampleCode).Filterable(false).Width(100);
columns.Bound(p => p.SampleItems).Filterable(false).Width(100);
})
.Pageable()
.Sortable()
.Scrollable()
.AutoBind(false)
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(2)
.Read(read => read.Action("Orders_Read", "CustomAjaxBinding"))
)
)
}
Controller
public class CustomAjaxBindingController : Controller
{
//
// GET: /CustomAjaxBinding/
public ActionResult Index()
{
return View("CustomAjaxbind");
}
public ActionResult Orders_Read([DataSourceRequest(Prefix = "grid12")]DataSourceRequest request)
{
string sortField = "SampleDescription";
string sortDirection = string.Empty;
if (request.Sorts != null)
{
foreach (SortDescriptor sortDescriptor in request.Sorts)
{
sortField = sortDescriptor.Member;
if (sortDescriptor.SortDirection == ListSortDirection.Ascending)
{
sortDirection = "Ascending";
}
else
{
sortDirection = "Descending";
}
}
}
int total = 1;
int myPageSize = 2;
if(request.PageSize !=0)
{
myPageSize = request.PageSize;
}
IEnumerable<Sample> currentSamples = GetSubsetEmployees(request.Page - 1, myPageSize, out total, sortField, sortDirection);
var result = new DataSourceResult()
{
Data = currentSamples,
Total = total // Total number of records
};
return Json(result);
}
public IEnumerable<Sample> GetSubsetEmployees(int pageIndex, int pageSize, out int itemCount, string sortField, string sortDirection)
{
IEnumerable<Sample> samples = GetSamples();
itemCount = samples.ToList().Count;
var selector = new Func<Sample, object>(e => e.GetType().GetProperty(sortField).GetValue(e, null));
var query = sortDirection.Equals("descending", StringComparison.OrdinalIgnoreCase)
? samples.OrderByDescending(selector)
: samples.OrderBy(selector);
List<Sample> currentPageEmployees = query
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
return currentPageEmployees;
}
public static IEnumerable<Sample> GetSamples()
{
List<Sample> sampleAdd = new List<Sample>();
Sample s12 = new Sample();
s12.SampleCode = "1";
s12.SampleDescription = "A";
s12.SampleItems = "newone";
Sample s2 = new Sample();
s2.SampleCode = "2";
s2.SampleDescription = "B";
s2.SampleItems = "oldone";
Sample s3 = new Sample();
s3.SampleCode = "3";
s3.SampleDescription = "C";
s3.SampleItems = "latestone";
Sample s4 = new Sample();
s4.SampleCode = "4";
s4.SampleDescription = "D";
s4.SampleItems = "latestoneitem";
sampleAdd.Add(s12);
sampleAdd.Add(s2);
sampleAdd.Add(s3);
sampleAdd.Add(s4);
return sampleAdd;
}
}
Model
namespace KendoUIMvcSample.Models
{
public class SampleModel
{
public List<Sample> samples;
}
public class Sample
{
public string SampleDescription { get; set; }
public string SampleCode { get; set; }
public string SampleItems { get; set; }
}
}
I had the same problem as yours and finally found the solution recently after consuming days on investigating the problem. I post it here if someone else faced the same issue.
You need to remove Prefix from your parameter:
public ActionResult Orders_Read([DataSourceRequest(Prefix = "grid12")]DataSourceRequest request)
Converted to:
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
I don't know if this is a bug from Kendo or not! But in this scenario grid can't be found by Prefix defined.
You can find an example here