ASP NET MVC - Form in view - c#

i have a problem in my asp.net view. I'v got a foreach loop, and i can't put my first iteration into my form.
That's the code:
<div id="#item.Name" class="tab-pane fade in active">
<div class="row">
#{int i = 0;}
#foreach (var prod in item.Products.Where(p => p.Type_Id == item.Id && p.IsDeleted != true))
{
using (Html.BeginForm("AddOrderRow", "Orders", new { enctype = "multipart/form-data", #class = "form-inline" }))
{
<input type="hidden" value="#ViewBag.orderId" name="Order_Id" />
<input type="hidden" value="#prod.Id" name="ProductID" />
<input type="hidden" value="#prod.Price" name="Price" />
<div class="col-sm-3" style="padding-bottom:20px">
<div align="center">
<button style="background-color:transparent; border-color:transparent">
<img class="img-responsive" src='#VirtualPathUtility.ToAbsolute(String.Format("{0}/{1}", System.Configuration.ConfigurationManager.AppSettings["ProdUploadPath"], prod.Image))' style="max-height: 100px" data-toggle="tooltip" title="#prod.Name">
</button>
</div>
</div>
if (i % 4 == 3)
{
#:</div><div class="row">
}
i++;
}
}
</div>
</div>
And that's how it look:
As you can see, only first div into first row is out of my form.

my suggest if you want save list, use save list not iteration form
example controller here;s the one when i learn mvc hahaha
public ActionResult Create(int? area, string now, string search, string message)
{
ViewBag.Area = new SelectList(CoreList.GetDropdown("UnitArea"), "DropdownId", "Value", area);
ViewBag.SelectedArea = area;
var newdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
IFormatProvider culture = new CultureInfo(CultureInfo.CurrentCulture.Name, true);
if (!string.IsNullOrWhiteSpace(now))
{
DateTime.TryParse(now, culture, DateTimeStyles.AssumeLocal, out newdate);
}
ViewBag.dateFilter = newdate.ToString(CultureInfo
.GetCultureInfo(CultureInfo.CurrentCulture.Name)
.DateTimeFormat.ShortDatePattern);
ViewBag.Search = search;
var attendances = (from p in db.MstUnitDriverPairings
join x in db.TrnAttendanceUnits
.Where(o => o.PresentDate.Value.Year == newdate.Year &&
o.PresentDate.Value.Month == newdate.Month &&
o.PresentDate.Value.Day == newdate.Day)
on p.UnitId equals x.UnitId into j1
from x in j1.DefaultIfEmpty()
join v in db.TrnAttendanceUnits.OrderByDescending(o => o.PresentDate).Where(o => o.ClockOut == null && o.PresentDate < newdate)
on p.UnitId equals v.UnitId into jd1
from v in jd1.DefaultIfEmpty()
join y in db.TrnAttendanceDrivers.Where(o => o.PresentDate == newdate)
on p.DriverId equals y.DriverId into j2
from y in j2.DefaultIfEmpty()
join z in db.TrnAttendanceDrivers.OrderByDescending(o => o.PresentDate).Where(o => o.ClockOut == null && o.PresentDate < newdate)
on p.DriverId equals z.DriverId into jd2
from z in jd2.DefaultIfEmpty()
where (area == null ? true : p.MstUnits.UnitArea == area)
&& (string.IsNullOrEmpty(search) ? true : p.MstDrivers.DriverName.ToLower().Contains(search.ToLower())
|| p.MstUnits.PoliceNo.ToLower().Contains(search.ToLower()))
&& p.MstUnits.UnitPrimary == true
select new Attendance
{
DriverId = p.DriverId,
DriverName = p.MstDrivers.DriverName,
DriverIn = y.ClockIn == null ? false : true,
DriverOut = y.ClockOut == null ? false : true,
DriverInDate = y.ClockIn,
DriverInDateBefore = z.ClockIn,
DriverOutDate = y.ClockOut,
DriverOutDateBefore = z.ClockOut,
UnitId = p.UnitId,
PoliceNumber = p.MstUnits.PoliceNo,
UnitIn = x.ClockIn == null? false : true,
UnitOut = x.ClockOut == null ? false : true,
UnitInDate = x.ClockIn,
UnitInDateBefore = v.ClockIn,
UnitOutDate = x.ClockOut,
UnitOutDateBefore = v.ClockOut
}).ToList();
return View(attendances);
}
[HttpPost]
public ActionResult AttendanceSave(List<Attendance> Models, string presentDate, int? area, string search)
{
string message = string.Empty;
var newdate = new DateTime();
IFormatProvider culture = new CultureInfo(CultureInfo.CurrentCulture.Name, true);
if (DateTime.TryParse(presentDate, culture, DateTimeStyles.AssumeLocal, out newdate))
{
foreach (var item in Models)
{
TrnAttendanceDriver trnAttendanceDriver = db.TrnAttendanceDrivers.FirstOrDefault(o => o.PresentDate == newdate && o.DriverId == item.DriverId);
TrnAttendanceUnit trnAttendanceUnit = db.TrnAttendanceUnits.FirstOrDefault(o => o.PresentDate == newdate && o.UnitId == item.UnitId);
if (trnAttendanceDriver != null)
{
if (item.DriverIn && item.DriverInDate != null) trnAttendanceDriver.ClockIn = item.DriverInDate;
if (item.DriverOut && item.DriverOutDate != null)
{
trnAttendanceDriver.ClockOut = item.DriverOutDate;
trnAttendanceDriver.Status = false;
}
}
else
{
if (item.DriverIn)
{
var newDriverAttendance = new TrnAttendanceDriver();
newDriverAttendance.DriverId = item.DriverId;
newDriverAttendance.ClockIn = item.DriverInDate;
newDriverAttendance.PresentDate = newdate;
newDriverAttendance.Status = true;
db.TrnAttendanceDrivers.Add(newDriverAttendance);
}
}
if (trnAttendanceUnit != null)
{
if (item.UnitIn && item.UnitInDate != null) trnAttendanceUnit.ClockIn = item.UnitInDate;
if (item.UnitOut && item.UnitOutDate != null)
{
trnAttendanceUnit.ClockOut = item.UnitOutDate;
trnAttendanceUnit.Status = false;
}
}
else
{
if (item.UnitIn)
{
var newUnitAttendance = new TrnAttendanceUnit();
newUnitAttendance.UnitId = item.UnitId;
newUnitAttendance.ClockIn = item.UnitInDate;
newUnitAttendance.PresentDate = newdate;
newUnitAttendance.Status = true;
db.TrnAttendanceUnits.Add(newUnitAttendance);
}
}
}
}
try
{
db.SaveChanges();
}
catch //(Exception ex)
{
throw;
}
return RedirectToAction("Index","Transaction/Attendance", new {area, search, message, now = presentDate });
}
here's the model
public class Attendance
{
public int DriverId { get; set; }
[Display(Name = "Name")]
public string DriverName { get; set; }
[Display(Name = "Driver In")]
public bool DriverIn { get; set; }
[DataType(DataType.DateTime)]
public DateTime? DriverInDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime? DriverOutDateBefore { get; set; }
[DataType(DataType.DateTime)]
public DateTime? DriverInDateBefore { get; set; }
[Display(Name = "Driver Out")]
public bool DriverOut { get; set; }
[DataType(DataType.DateTime)]
public DateTime? DriverOutDate { get; set; }
public int UnitId { get; set; }
[Display(Name = "Police Number")]
public string PoliceNumber { get; set; }
[Display(Name = "Unit In")]
public bool UnitIn { get; set; }
[DataType(DataType.DateTime)]
public DateTime? UnitInDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime? UnitOutDateBefore { get; set; }
[DataType(DataType.DateTime)]
public DateTime? UnitInDateBefore { get; set; }
[Display(Name = "Unit Out")]
public bool UnitOut { get; set; }
[DataType(DataType.DateTime)]
public DateTime? UnitOutDate { get; set; }
}
and here's view
#model List<Solution.Web.Areas.Transaction.Models.Attendance>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<nav class="navbar navbar-white" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav2">
<span class="sr-only">Toggle</span>
<span class="glyphicon glyphicon-search"></span>
</button>
<a class="navbar-brand">Search</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="nav2">
<form class="navbar-form navbar-right" role="search">
<div class="form-group">
#Html.DropDownList("Area", string.Empty)
</div>
<div class="form-group">
<input type="text" name="now" id="dateFilter" class="form-control datepicker" value="#ViewBag.dateFilter" />
</div>
<div class="form-group">
<input type="text" name="Search" class="form-control" value="#ViewBag.Search" placeholder="Search" />
</div>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
</div>
<!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
#using (Html.BeginForm("AttendanceSave", "Attendance", FormMethod.Post))
{
<input type="hidden" name="presentDate" value="#ViewBag.dateFilter" />
<input type="hidden" name="area" value="#ViewBag.SelectedArea" />
<input type="hidden" name="search" value="#ViewBag.Search" />
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Attendance</h3>
</div>
<div class="table-responsive">
<table class="table table-striped">
<tr>
<th colspan="3">
Driver
</th>
<th colspan="3">
Unit
</th>
</tr>
<tr>
<th>
Name
</th>
<th>
In
#Html.CheckBox("drivercheckInHead")
</th>
<th>
Out
#Html.CheckBox("drivercheckOutHead")
</th>
<th>
Police Number
</th>
<th>
In
#Html.CheckBox("unitcheckInHead")
</th>
<th>
Out
#Html.CheckBox("unitcheckOutHead")
</th>
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
#Html.Hidden("Models[" + i + "].DriverId", Model[i].DriverId)
#Html.Hidden("Models[" + i + "].UnitId", Model[i].UnitId)
<td>
#Html.DisplayFor(m => m[i].DriverName)
</td>
<td>
#if (Model[i].DriverIn && Model[i].DriverOut)
{
#Html.Hidden("Models[" + i + "].DriverIn", Model[i].DriverIn)
#Html.Hidden("Models[" + i + "].DriverInDate", Model[i].DriverInDate)
#Model[i].DriverInDate.Value.ToString("dd MMMM yyyy HH:mm")
}
else
{
if (Model[i].DriverOutDateBefore == null && Model[i].DriverInDateBefore != null)
{
<label class="label label-danger">
#Model[i].DriverInDateBefore.Value.ToString("dd MMMM yyyy HH:mm")
</label>
}
else
{
<div class="input-group input-group-sm">
<span class="input-group-addon">
#Html.CheckBox("Models[" + i + "].DriverIn", Model[i].DriverIn, new { #class = "drivercheckIn" })
</span>
#Html.TextBox("Models[" + i + "].DriverInDate", Model[i].DriverInDate, new { #class = "datetimepicker drivercheckInDate" })
</div>
}
}
</td>
<td>
#if (Model[i].DriverIn && Model[i].DriverOut)
{
#Html.Hidden("Models[" + i + "].DriverOut", Model[i].DriverOut)
#Html.Hidden("Models[" + i + "].DriverOutDate", Model[i].DriverOutDate)
#Model[i].DriverOutDate.Value.ToString("dd MMMM yyyy HH:mm")
}
else
{
if (Model[i].DriverIn)
{
<div class="input-group input-group-sm">
<span class="input-group-addon">
#Html.CheckBox("Models[" + i + "].DriverOut", Model[i].DriverOut, new { #class = "drivercheckOut" })
</span>
#Html.TextBox("Models[" + i + "].DriverOutDate", Model[i].DriverOutDate, new { #class = "datetimepicker drivercheckOutDate" })
</div>
}
else
{
<span class="label label-info">Need driver in</span>
}
}
</td>
<td>
#Html.DisplayFor(m => m[i].PoliceNumber)
</td>
<td>
#if (Model[i].UnitIn && Model[i].UnitOut)
{
#Html.Hidden("Models[" + i + "].UnitIn", Model[i].UnitIn)
#Html.Hidden("Models[" + i + "].UnitIn", Model[i].UnitInDate)
#Model[i].UnitInDate.Value.ToString("dd MMMM yyyy HH:mm")
}
else
{
if (Model[i].UnitOutDateBefore == null && Model[i].UnitInDateBefore != null)
{
<label class="label label-danger">
#Model[i].UnitInDateBefore.Value.ToString("dd MMMM yyyy HH:mm")
</label>
}
else
{
<div class="input-group input-group-sm">
<span class="input-group-addon">
#Html.CheckBox("Models[" + i + "].UnitIn", Model[i].UnitIn, new { #class = "unitcheckIn" })
</span>
#Html.TextBox("Models[" + i + "].UnitInDate", Model[i].UnitInDate, new { #class = "datetimepicker unitcheckInDate" })
</div>
}
}
</td>
<td>
#if (Model[i].UnitIn && Model[i].UnitOut)
{
#Html.Hidden("Models[" + i + "].UnitOut", Model[i].UnitOut)
#Html.Hidden("Models[" + i + "].UnitOutDate", Model[i].UnitOutDate)
#Model[i].UnitOutDate.Value.ToString("dd MMMM yyyy HH:mm")
}
else
{
if (Model[i].UnitIn)
{
<div class="input-group input-group-sm">
<span class="input-group-addon">
#Html.CheckBox("Models[" + i + "].UnitOut", Model[i].UnitOut, new { #class = "unitcheckOut" })
</span>
#Html.TextBox("Models[" + i + "].UnitOutDate", Model[i].UnitOutDate, new { #class = "datetimepicker unitcheckOutDate" })
</div>
}
else
{
<span class="label label-info">Need unit in</span>
}
}
</td>
</tr>
}
</table>
</div>
#if (Model.Count() > 0)
{
<div class="panel-footer">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-ok"> Submit</span>
</button>
</div>
}
</div>
}
hope this helps, sorry for my bad codes, hehehe

Related

CS1061: 'Page' does not contain a definition for 'cBannerImage' Error in mvc5

I have a form view where I get the page content name and picture
But i got this error:
"CS1061: 'Page' does not contain a definition for 'cBannerImage' and no accessible extension method 'cBannerImage' accepting a first argument of type 'Page' could be found (are you missing a using directive or an assembly reference?)"
why am i getting this error and how can i fix it?
Page Model :
namespace ArilWebYonetimPaneli.Models
{
public class Page
{
public int? iPageId { get; set; }
[Display(Name = "Dil")]
public int? iLanguageId { get; set; }
[Display(Name = "Kuşak Resmi")]
public string cBannerImage { get; set; }
[Display(Name = "Sayfa Başlığı")]
public string cTitle { get; set; }
[Display(Name = "Sayfa içeriği")]
[AllowHtml]
public string cContent { get; set; }
[Display(Name = "Aktif")]
public int iIsActive { get; set; }
[Display(Name = "Aktif")]
public int iActive { get; set; }
[Display(Name = "Pasif")]
public int iPasive { get; set; }
public DateTime dUpdateDate { get; set; }
public string cUpdateDate { get; set; }
public DateTime dInsertDate { get; set; }
}
}
PageController:
[HttpGet]
public ActionResult AddUpdate(string id)
{
try
{
if (Session["iUserId"] == null && GetCookie("iUserId") == null)
{
return Redirect("/AdminUsers/Login");
}
int iUserLogin = 0;
if (Session["iUserId"] != null && Convert.ToInt32(Session["iUserId"]) > 0)
{
iUserLogin = Convert.ToInt32(Session["iUserId"]);
}
else if (GetCookie("iUserId") != null && Convert.ToInt32(GetCookie("iUserId")) > 0)
{
iUserLogin = Convert.ToInt32(GetCookie("iUserId"));
}
ViewBag.LanguagesList = new Models.Languages().Send();
if (!String.IsNullOrEmpty(id))
{
int iPageId = 0;
if (int.TryParse(id, out iPageId) && iPageId > 0)
{
using (Data.DataClassesDataContext dc = new Data.DataClassesDataContext())
{
var read = (from table in dc.Pages
where
table.iPageId == iPageId &&
(table.iActive == 0 || table.iActive == 1)
select new Models.Page
{
iPageId = table.iPageId,
iLanguageId = (int)table.iLanguageId,
cBannerImage = table.cBannerImage,
cTitle = table.cTitle,
cContent = table.cContent,
iIsActive = (int)table.iActive,
dUpdateDate = (table.dUpdateDate != null ? Convert.ToDateTime(table.dUpdateDate) : Convert.ToDateTime("1900-01-01")),
cUpdateDate = String.Format("{0:dd.MM.yyyy, HH:mm}", (table.dUpdateDate != null ? Convert.ToDateTime(table.dUpdateDate) : Convert.ToDateTime("1900-01-01"))),
}).FirstOrDefault();
return View(read);
}
}
else
{
ViewBag.iSonuc = -2;
}
}
}
catch (Exception Ex)
{
ViewBag.iSonuc = -2;
}
return View();
}
And AddUpdate View:
#model ArilWebYonetimPaneli.Models.Page
#section Styles{
#*JQUERY UI*#
<link href="~/assets/global/plugins/jquery-ui/jquery-ui.min.css" rel="stylesheet" />
#*SELECT2*#
<link href="../assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/ckeditor/ckeditor.js"></script>
<script src="~/ckfinder/ckfinder.js"></script>
}
#{
ViewBag.Title = "AddUpdate";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="content">
#using (Html.BeginForm("AddUpdate", "Page", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-body">
#Html.HiddenFor(model => model.iPageId)
<div class="form-group">
#Html.LabelFor(model => model.iLanguageId)
#Html.DropDownListFor(x => x.iLanguageId, new SelectList(ViewBag.LanguagesList, "iLanguagesId", "cLanguagesName"), "Lütfen dil seçin ...", new { #class = "form-control", #tabindex = 1 })
</div>
#Html.HiddenFor(model => model.cBannerImage)
#Html.LabelFor(model => model.cBannerImage)
<div class="fileinput fileinput-new" data-provides="fileinput2" id="fileinput2">
#if (Model != null && Model.iPageId > 0 && Model.iPageId != null)
{
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="/Images/#Model.cBannerImage" id="imgId" alt="" />
</div>
}
else
{
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" />
</div>
}
<div>
<div>
<span class="btn default btn-file">
<input type="file" name="file" id="file2">
</span>
Remove
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cTitle)
#Html.TextBoxFor(model => model.cTitle, new { #class = "form-control", placeholder = "Lütfen sayfa başlığı giriniz..." })
</div>
<div class="form-group last">
#Html.LabelFor(model => model.cContent)
#Html.TextAreaFor(model => model.cContent, new { #class = "ckeditor form-control", placeholder = "Lütfen içerik giriniz...", #name = "editor1", #rows = "10" })
</div>
<div class="form-group">
<div class="mt-radio-inline">
<label class="mt-radio">
#Html.RadioButtonFor(model => model.iIsActive, 1, new { #name = "optionsRadios", #id = "iActive", #value = "option1", #checked = "checked" }) Aktif
<span></span>
</label>
<label class="mt-radio">
#Html.RadioButtonFor(model => model.iIsActive, 0, new { #name = "optionsRadios", #id = "iPasive", #value = "option1" }) Pasif
<span></span>
</label>
</div>
</div>
#{ Html.RenderPartial("/Views/Partials/WarningMessages.cshtml"); }
</div>
<hr />
if (Model != null && Model.iPageId > 0)
{
<div class="form-actions right"><button type="submit" class="btn green">Güncelle</button></div>
}
else
{
<div class="form-actions right"><button type="submit" class="btn green">Ekle</button></div>
}
}
</div>
#section Scripts{
<script src="~/MjrScripts/upload.js"></script>
<script type="text/javascript">
var editor = CKEDITOR.instances['editor1'];
if (editor) { editor.destroy(true); }
CKEDITOR.replace('editor1', {
enterMode: CKEDITOR.ENTER_BR,
});
CKFinder.setupCKEditor(null, '#Url.Content("~/ckfinder/")');
</script>
<script type="text/javascript">
$(function () {
$("#iUrl").select2();
$("#iLanguageId").select2();
});
</script>
}

ASP.Net Core Populating Dropdown with List Model item

I am trying to populate a "Company" dropdown but I can not get the Razor syntax correct on it.
With the below code it makes my modal just not pop up. JS gets an undefined error for the company field and it errors out. If i remove #Html.DropDownListFor(c => c.SelectedCompany, Model.CompanyLists, "- Please select a state -", new { #class = "form-control" }) then the modal pops up fine, just with no items populated.
Any idea what I am doing wrong? I was using this article for reference. https://nimblegecko.com/using-simple-drop-down-lists-in-ASP-NET-MVC/ ; however, it has a hard-coded list instead of one pulling from DB.
<div class="tab-pane fade show active" id="user" role="tabpanel" aria-labelledby="user-tab">
<form method="post" class="mt-3">
<div class="form-group row text-center">
<label asp-for="Id" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input disabled asp-for="Id" class="formField inputDisabled" disabledclass="form-control">
</div>
</div>
<div class="form-group row text-center">
<label asp-for="FirstName" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="FirstName" class="formField" />
<span asp-validation-for="FirstName" class="text-danger"></span>
/div>
</div>
<div class="form-group row text-center">
<label asp-for="LastName" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="LastName" class="formField" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="Title" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="Title" class="formField" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="Email" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="Email" class="formField" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="UserName" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="UserName" class="formField" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="CompanyLists" class="col-sm-3 text-right col-form-label labelFont"></label>
#*ISSUE IS HERE--------------------------------------------------------------------------------------*#
<div class="col-md-5">
#Html.DropDownListFor(c => c.SelectedCompany, Model.CompanyLists, "- Please select a state -", new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.SelectedCompany, "", new { #class = "text-danger" })
</div>
#*------------------------------------------------------------------------------------------*#
</div>
<div class="form-group row text-center">
<label asp-for="Address" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="Address" class="formField" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="City" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="City" class="formField" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="State" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="State" class="formField" />
<span asp-validation-for="State" class="text-danger"></span>
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<button type="submit" class="btn btn-primary padFloat btnBlue" asp-action="EditUser" asp-controller="Administration" asp-route-id="#Model.Id">Update</button>
<a asp-action="UserMaint" class="btn btn-primary padFloat btnRed">Cancel</a>
</form>
</div>
Model:
namespace PortalDev.Models.ViewModels
{
public class EditUserViewModel
{
public EditUserViewModel()
{
Claims = new List<Claim>();
Roles = new List<Role>();
//CompanyLists = new List<ICompanyRepository>();
CompanyLists = new List<CompanyList>();
}
//ROLES ---------------------------------------------
public class Role
{
public string RoleName { get; set; }
public string RoleID { get; set; }
public bool IsSelected { get; set; }
}
public List<Role> Roles { get; set; }
//CLAIMS----------------------------------------------
public class Claim
{
public string ClaimType { get; set; }
public string ClaimID { get; set; }
public bool IsSelected { get; set; }
}
public List<Claim> Claims { get; set; }
//COMPANY DROPDOWN--------------------------------------
public class CompanyList
{
public string CompanyName { get; set; }
public int CompanyID { get; set; }
}
[Display(Name = "Company")]
public List<CompanyList> CompanyLists { get; set; } //List of Companies for dropdown
public string SelectedCompany { get; set; }
//USER INFORMATION --------------------------------------
public string Id { get; set; }
//[Required]
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
}
Method:
// EDIT USER : GET-----------------------------------------------------
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
//GET USER INFORMATION - EXIT IF USER DOESN'T EXIST
var user = await userManager.FindByIdAsync(id);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
return View("NotFound");
}
//USER INFORMATION ---------------------------------------
var model = new EditUserViewModel
{
Id = user.Id,
Email = user.Email,
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName,
Title = user.Title,
Address = user.Address,
City = user.City,
State = user.State,
//CompanyId = user.CompanyId
};
// ViewBag.SelectedCommpany = user.CompanyId;
//COMPANY DROPDOWN INFO------------------------------------
var company = from c in companyRepository.GetCompanys() select c;
foreach (var c in company)
{
////Store this inforamtion into the company list in the viewmodel
var companyinfo = new EditUserViewModel.CompanyList
{
CompanyName = c.CompanyName,
CompanyID = c.CompanyId
};
model.CompanyLists.Add(companyinfo);
};
//GET LIST OF ROLES(RoleID, RoleName)
var roles = roleManager.Roles;
foreach (var RoleName in roles)
{
//Execute identity method to get full information for the Role and store into an object (roleinfo)
var roleString = RoleName.Name;
var fullRoleInfo = await roleManager.FindByNameAsync(roleString);
//Store this information into the Role list in the viewmodel
var roleinfo = new EditUserViewModel.Role
{
RoleName = fullRoleInfo.Name,
RoleID = fullRoleInfo.Id,
};
if (await userManager.IsInRoleAsync(user, roleString))
{
roleinfo.IsSelected = true;
}
else
{
roleinfo.IsSelected = false;
}
model.Roles.Add(roleinfo);
};
//**************************************************************************************************************************************************************
//IDENTITY CLAIM INFORMATION ------------------------------
var existingUserClaims = await userManager.GetClaimsAsync(user);
foreach (Claim claim in ClaimStore.AllClaims)
{
var userClaims = new EditUserViewModel.Claim
{
ClaimType = claim.Type
};
if (existingUserClaims.Any(c => c.Type == claim.Type && c.Value == "true"))
{
userClaims.IsSelected = true;
}
else
{
userClaims.IsSelected = false;
}
model.Claims.Add(userClaims);
}
ViewBag.UserModel = model;
return PartialView("~/Views/Modals/_EditUserModalPartial.cshtml", model);
}
Follow my example
Here is my DropDownListFor;
#Html.DropDownListFor(model => Model.SelectedDropDownValue, new SelectList(Model.DropDownListAutoPopulate), "Quarter - Year", new { #class = "form-control btn-primary form-control", #id = "QuarterYearConcat", #onchange = #"form.submit();" })
Model.SelectedDropDownValue is the selected value passed back from the controller
public List<string> DropDownListAutoPopulate { get; set; }
is the list that will populate the dropdown. Which is my viewModel model.
Here is my full model for the viewModel
namespace MoCApp.ViewModels
{
public class SLGAdminCreateViewModel
{
public SLGHeader SLGHeader;
[Range(-100.00, 100.00, ErrorMessage = "Value must be between -100 and 100")]
public decimal? TotalBudget { get; set; }
[Range(-100.00, 100.00, ErrorMessage = "Value must be between -100 and 100")]
public decimal? TotalLaborBudget { get; set; }
public List<QuarterWeekType> DropDownList { get; set; }
public SLGQuarterDetails SLGQuarterList { get; set; }
public QuarterWeekType Dropdown { get; set; }
public string SelectedDropDownValue { get; set; }
public List<string> DropDownListAutoPopulate { get; set; }
}
}
Here is my Get method in relation to the model and view.
// GET: SLG/CreateAdmin
[Authorize(Roles = "WFL_APP_MOCHUB-Admins,WFL_APP_SLG-Admins,Managers,WFL_ROLE_StoreManagmentTeams")]
public ActionResult CreateAdmin(SLGAdminCreateViewModel value)
{
// ViewModel for Both Forms
var viewModel = new SLGAdminCreateViewModel
{
SLGHeader = new SLGHeader(),
DropDownList = new List<QuarterWeekType>(),
DropDownListAutoPopulate = new List<string>(),
TotalBudget = null,
TotalLaborBudget = null
};
// Formating returned value for query to set values.
if (value.SelectedDropDownValue != null)
{
var QuarterYear = value.SelectedDropDownValue.Replace("Q", "").Replace(":", "").Replace(" ", "");
var Quarter = decimal.Parse(QuarterYear.Substring(0, 1), CultureInfo.InvariantCulture);
var Year = decimal.Parse(QuarterYear.Substring(1, 4), CultureInfo.InvariantCulture);
var TotalBudgetList = db.QuarterDetails.Where(x => x.Quarter == Quarter && x.Year == Year && x.Store == 1 && x.Department == "total")
.ToList();
foreach (var x in TotalBudgetList) { viewModel.TotalBudget = x.TotalBudget; viewModel.TotalLaborBudget = x.TotalLaborBudget; };
}
// Format dropdown list
viewModel.DropDownList = db.SLGHeaderTemplates.Where(x => x.Year > 2018 && x.Week == 1).Select(x => new QuarterWeekType { Year = x.Year, Quarter = x.Quarter, QuarterYearConcat = "" }).ToList();
foreach (var item in viewModel.DropDownList)
{
item.QuarterYearConcat = "Q" + Convert.ToInt32(item.Quarter) + " : " + Convert.ToInt32(item.Year);
}
foreach (var x in viewModel.DropDownList) { viewModel.DropDownListAutoPopulate.Add(x.QuarterYearConcat); };
return View(viewModel);
}
If you follow my example and have your model, view and controller in the same relations. You will be golden.
Don't mind my logic with me foreaching through one object and putting it into another list. Just know where your list goes in the DropDownListFor statement and how it is related to your viewModel and Controller.

How to implement pagination in MVC with bootstrap datepicker?

Friends, I have implemented a solution type ASP.NetCore with a project MVC. I have a view in which I used https://github.com/cloudscribe/cloudscribe.Web.Pagination for pagination. **Honestly I took the example and used it. But I don't get the detail about this code example.
The problem that I have now is that, I have to include filters, like datepicker range. So I am using bootstrap datepicker. But the pagination stopped working.
The pagination gets this parameters in querytrings to work: pageNumber, pageSize and query. When I send the request of the filter date, I can get the dates selected in the controller, but the parameters of pagination get in null.
This is an URL example with pagination working fine: http://localhost/pager?query=1&pagesize=10&pageNumber=2
This is an URL when I send the request in the button 'Apply' with dates range, and pagination died without its parameters like 'query': http://localhost/pager?startDate=11/04/2019&endDate=11/11/2019
I suppose I have to send the current querystring in the request too, but I'm not sure, I'm kind of new at this technology. Thanks for any help.
My view →
#using (Html.BeginForm("Details", "Movements", routeValues: new { pageNumber = #Model.UserMovementsResults.PageNumber, pageSize = #Model.UserMovementsResults.PageSize, query = #Model.Query }, FormMethod.Get))
{
<br />
<div style="border: 2px solid #dee2e6;padding: 5px;width: 50%;">
<br />
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBoxFor(model => model.StartDateFilter, "{0:d MMM yyyy}", new
{
id = "StartDateFilter",
#class = "input-sm form-control",
#readonly = "readonly"
})
<span class="input-group-addon"> To </span>
#Html.TextBoxFor(model => model.EndDateFilter, "{0:d MMM yyyy}", new
{
id = "EndDateFilter",
#class = "input-sm form-control",
#readonly = "readonly"
})
</div>
<br />
<input type="submit" value="Apply" class="btn btn-primary" name="Apply" />
</div>
<br />
<br />
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Date)
</th>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Description)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserMovementsResults.Data)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</tbody>
</table>
<div>
<cs-pager cs-paging-pagesize="#Model.UserMovementsResults.PageSize"
cs-paging-pagenumber="#Model.UserMovementsResults.PageNumber"
cs-paging-totalitems="#Model.UserMovementsResults.TotalItems"
cs-pagenumber-param="pageNumber"
cs-show-first-last="true"
cs-suppress-empty-nextprev="true"
cs-remove-nextprev-links="false"
cs-suppress-inactive-firstlast="true"
cs-first-page-text="First"
cs-last-page-text="Last"
cs-pager-li-current-class="active"
cs-pager-li-non-active-class="disabled"
asp-controller="Movements"
asp-route-query="#Model.Query"
asp-route-pagesize="#Model.UserMovementsResults.PageSize"
asp-route-startDateFilter="#Model.StartDateFilter.GetValueOrDefault()"
asp-route-endDateFilter="#Model.EndDateFilter.GetValueOrDefault()"
asp-action="Details" cs-preserve-ambient-querystring="true"></cs-pager>
</div>
}
My Controller (I've tried to set the method HttpGet and HttpPost) →
[HttpGet]
public async Task<IActionResult> Details(int? pageNumber, int? pageSize, int? query, string startDate, string endDate)
{
if (query == null)
{
return NotFound();
}
DateTime startDateFilter = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime endDateFilter = DateTime.Now.EndOfWeek(DayOfWeek.Monday);
var userMovements = await GetUserMovements(user.Id, pageNumber, pageSize, query, startDateFilter, endDateFilter);
return View(userMovements);
}
}
My ViewModel →
public class UserMovementsViewModel
{
private DateTime? endDateFilter;
public UserMovementsViewModel()
{
UserMovementsResults = new PagedResult<UserMovementsResult>();
}
public string Query { get; set; } = string.Empty;
[Key]
public int Id { get; set; }
public int UserId { get; set; }
public PagedResult<UserMovementsResult> UserMovementsResults { get; set; } = null;
public DateTime? StartDateFilter { get; set; }
public DateTime? EndDateFilter
{
get => endDateFilter;
set
{
if (value != null)
{
endDateFilter = value;
endDateFilter = endDateFilter.Value.AddHours(23).AddMinutes(59).AddSeconds(59);
}
}
}
}
public class UserMovementsResult
{
public DateTime Date { get; set; }
public string Description { get; set; }
}
Here is a simple workaround like below:
1.add the following component in _ViewImports.cshtml:
#using cloudscribe.Web.Pagination
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper "*, cloudscribe.Web.Pagination"
2.Model:
public class UserMovements
{
public string Name { get; set; } = string.Empty;
public DateTime Date { get; set; } = DateTime.UtcNow;
public string Description { get; set; } = string.Empty;
}
public class ViewByDateViewModel
{
public ViewByDateViewModel()
{
UserMovements = new PagedResult<UserMovements>();
}
public PagedResult<UserMovements> UserMovements { get; set; }
public string[] Date { get; set; }
}
3.View(ViewByDate.cshtml):
#using System.Linq
#model ViewByDateViewModel
<form class="form-inline" role="form" asp-controller="Home" asp-action="ViewByDate" method="get" asp-antiforgery="false">
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBox("startDate", null, new
{
id = "startDate",
#class = "input-sm form-control",
})
<span class="input-group-addon"> To </span>
#Html.TextBox("endDate", null, new
{
id = "endDate",
#class = "input-sm form-control",
})
</div>
<input type="submit" value="Browse" class="btn btn-default" />
</form>
#if (Model.UserMovements.Data.Any())
{
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.UserMovements.Data)
{
<tr>
<td>#product.Name</td>
<td>#product.Date</td>
</tr>
}
</tbody>
</table>
<cs-pager cs-paging-pagesize="#Model.UserMovements.PageSize"
cs-paging-pagenumber="#Model.UserMovements.PageNumber"
cs-paging-totalitems="#Model.UserMovements.TotalItems"
cs-pagenumber-param="page"
asp-controller="Home"
asp-action="ViewByDate"
asp-route-categories="#Model.Date.ToCsv()"
asp-route-pagesize="#Model.UserMovements.PageSize"
cs-first-page-text="First"
cs-last-page-text="Last"
cs-previous-page-text="Prev"
cs-next-page-text="Next"></cs-pager>
}
#section Scripts
{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#startDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' });
$("#endDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
});
</script>
}
4.Controller:
public class HomeController : Controller
{
private const int DefaultPageSize = 10;
private List<UserMovements> allMovements = new List<UserMovements>();
public HomeController()
{
InitializeMovements();
}
private void InitializeMovements()
{
// Create a list of Movements.
for (var i = 0; i < 527; i++)
{
var userMovements = new UserMovements();
userMovements.Name = "UserMovements " + (i + 1);
var categoryIndex = i % 4;
if (categoryIndex > 2)
{
categoryIndex = categoryIndex - 3;
}
userMovements.Date = DateTime.Now.AddDays(i);
allMovements.Add(userMovements);
}
}
public IActionResult ViewByDate(string startDate, string endDate, int? page)
{
string[] dates = { startDate, endDate };
List<UserMovements> filtered;
var currentPageNum = page.HasValue ? page.Value : 1;
var offset = (DefaultPageSize * currentPageNum) - DefaultPageSize;
var model = new ViewByDateViewModel();
model.Date = dates ?? new string[0];
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
if (startDate == null && endDate == null)
{
filtered = this.allMovements.ToList();
}
else
{
filtered = this.allMovements
.Where(p => p.Date.Date >= DateTime.Parse(startDate) && p.Date.Date <= DateTime.Parse(endDate))
.ToList();
}
model.UserMovements.Data = filtered
.Skip(offset)
.Take(DefaultPageSize)
.ToList();
model.UserMovements.PageNumber = currentPageNum;
model.UserMovements.PageSize = DefaultPageSize;
model.UserMovements.TotalItems = filtered.Count;
return View(model);
}
}
5.Result:
UPDATE:
1.Model:
public class ViewByDateViewModel
{
private DateTime? endDateFilter;
public ViewByDateViewModel()
{
UserMovements = new PagedResult<UserMovements>();
}
public PagedResult<UserMovements> UserMovements { get; set; }
//public string[] Date { get; set; }
public DateTime? StartDateFilter { get; set; }
public DateTime? EndDateFilter
{
get => endDateFilter;
set
{
if (value != null)
{
endDateFilter = value;
endDateFilter = endDateFilter.Value.AddHours(23).AddMinutes(59).AddSeconds(59);
}
}
}
}
2.View:
#using System.Linq
#model ViewByDateViewModel
<form class="form-inline" role="form" asp-controller="Home" asp-action="ViewByDate" method="get" asp-antiforgery="false">
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBox("startDate", null, new
{
id = "startDate",
#class = "input-sm form-control",
})
<span class="input-group-addon"> To </span>
#Html.TextBox("endDate", null, new
{
id = "endDate",
#class = "input-sm form-control",
})
</div>
<input type="submit" value="Browse" class="btn btn-default" />
</form>
#if (Model.UserMovements.Data.Any())
{
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.UserMovements.Data)
{
<tr>
<td>#product.Name</td>
<td>#product.Date</td>
</tr>
}
</tbody>
</table>
<cs-pager cs-paging-pagesize="#Model.UserMovements.PageSize"
cs-paging-pagenumber="#Model.UserMovements.PageNumber"
cs-paging-totalitems="#Model.UserMovements.TotalItems"
cs-pagenumber-param="page"
asp-controller="Home"
asp-action="ViewByDate"
asp-route-pagesize="#Model.UserMovements.PageSize"
asp-route-startDateFilter="#Model.StartDateFilter"
asp-route-endDateFilter="#Model.EndDateFilter"
cs-first-page-text="First"
cs-last-page-text="Last"
cs-previous-page-text="Prev"
cs-next-page-text="Next"></cs-pager>
}
#section Scripts
{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#startDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' });
$("#endDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
});
</script>
}
3.Controller:
public IActionResult ViewByDate(string startDate, string endDate, int? page)
{
string[] dates = { startDate, endDate };
List<UserMovements> filtered;
var currentPageNum = page.HasValue ? page.Value : 1;
var offset = (DefaultPageSize * currentPageNum) - DefaultPageSize;
var model = new ViewByDateViewModel();
model.StartDateFilter = startDate==null? DateTime.Now:DateTime.Parse(startDate);
model.EndDateFilter = endDate == null ? DateTime.Now : DateTime.Parse(endDate);
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
if (startDate == null && endDate == null)
{
filtered = this.allMovements.ToList();
}
else
{
filtered = this.allMovements
.Where(p => p.Date.Date >= DateTime.Parse(startDate) && p.Date.Date <= DateTime.Parse(endDate))
.ToList();
}
model.UserMovements.Data = filtered
.Skip(offset)
.Take(DefaultPageSize)
.ToList();
model.UserMovements.PageNumber = currentPageNum;
model.UserMovements.PageSize = DefaultPageSize;
model.UserMovements.TotalItems = filtered.Count;
return View(model);
}
if you want to send by url,url would be like:https://localhost:44367/Home/ViewByDate?startdate=11-14-2019&enddate=11-27-2019
If anyone needs this too, here is how I got it → I was missing the setting of the parameters in the controller with ViewBag. Like this → ViewBag.StartDateFilter = starDate; Otherwise, It was becoming at null always, when I tried to change at another page. I don't why.
I used a hidden field too to save the "query" (in my case this is the user id) because when I sent the request submit in the button, this was losing its value too. What a mess !!
Here is a minified version
View:
<script src="~/lib/bootstrap/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<form class="form-inline" role="form" asp-controller="Movements" asp-action="Details" method="get" asp-antiforgery="false" asp-route-query="#ViewBag.Query">
<div>
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBox("startDate", null, new
{
id = "startDate",
#class = "input-sm form-control",
#readonly = "readonly"
})
<span class="input-group-addon"> To </span>
#Html.TextBox("endDate", null, new
{
id = "endDate",
#class = "input-sm form-control",
#readonly = "readonly"
})
</div>
<button asp-route-query="#ViewBag.Query" type="submit" value="Filter" name="Filter">Apply</button>
#Html.Hidden("Query", (object)ViewBag.Query)
</div>
</form>
<br />
<table>
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Date)
</th>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Description)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserMovementsResults.Data)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</tbody>
</table>
<div>
<cs-pager cs-paging-pagesize="#Model.UserMovementsResults.PageSize"
cs-paging-pagenumber="#Model.UserMovementsResults.PageNumber"
cs-paging-totalitems="#Model.UserMovementsResults.TotalItems"
cs-pagenumber-param="pageNumber"
asp-controller="Movements"
asp-action="Details"
asp-route-query="#ViewBag.Query"
asp-route-pagesize="#Model.UserMovementsResults.PageSize"
cs-preserve-ambient-querystring="true"
asp-route-startDate="#ViewBag.StartDateFilter"
asp-route-endDate="#ViewBag.EndDateFilter">
</cs-pager>
</div>
Controller:
[HttpGet]
public async Task<IActionResult> Details(int? pageNumber, UserMovementsViewModel userMovementsViewModel)
{
userMovementsViewModel.StartDateFilter = DateTime.ParseExact(userMovementsViewModel.StartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
userMovementsViewModel.EndDateFilter = DateTime.ParseExact(userMovementsViewModel.EndDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).SetEndOfDay();
var userMovements = await GetUserMovements(pageNumber, userMovementsViewModel).ConfigureAwait(true);
ViewBag.StartDateFilter = userMovementsViewModel.StartDateFilter.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
ViewBag.EndDateFilter = userMovementsViewModel.EndDateFilter.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
ViewBag.Query = userMovementsViewModel.Query;
return View(userMovements);
}
My Class:
public class UserMovementsViewModel
{
public UserMovementsViewModel()
{
UserMovementsResults = new PagedResult<UserMovementsResult>();
}
public string Query { get; set; } = string.Empty;
public PagedResult<UserMovementsResult> UserMovementsResults { get; set; } = null;
public DateTime? StartDateFilter { get; set; }
public DateTime? EndDateFilter { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
}

MVC returns null instead of a IList<> object

I am using MVC .NET 4.5 and my form returns a null instead of a List of objects. At the same time I have this Jquery function that adds HTML to the form, but it doesn't just adds the HTML, it makes the form POST to the controller. I don't know if both of these are related, but just in case I am providing all the relevant code. Please help.
Model class:
public class BidModels
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id{ set; get;}
//Who put the bid...
public string UserId { set; get; }
//The Compnay putting the bid
[ForeignKey("CompanyModels")]
public int? CompanyId { set; get; }
public virtual CompanyModels CompanyModels { set; get; }
//The position being bid on
[ForeignKey("ProjectPositionModels")]
public int? PositionId { set; get; }
public virtual ProjectPositionModels ProjectPositionModels { set; get; }
//How much?
[DataType(DataType.Currency)]
public int? BidAmount { set; get; }
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddBid(IList<BidModels> bids)
{
//Iterate the list for every new bid in it.
var userId = User.Identity.GetUserId();
var companyId = db.CompanyModels.Single(x => x.UserId == userId);
//checking for content
Console.Write(bids.ToString());
//db.BidModels.Add();
// await db.SaveChangesAsync();
return View("Index");
}
partial view:
<form method="post" action="/BidModels/AddBid">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Make a Bid</h4>
</div>
<div class="modal-body">
<div class="row">
<div style="margin-left:15px;">
<button id="add"><span class="glyphicon glyphicon-plus"></span></button>
<button id="remove"><span class="glyphicon glyphicon-minus"></span></button>
</div>
#Html.AntiForgeryToken()
<table class="table" id="form-table">
<tr>
<th>
<strong>Position</strong>
</th>
<th>
<strong>Bid Amount</strong>
</th>
</tr>
<tr class="form-row">
<td>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<input type="hidden" name="bid[0].Id" value="" />
<input type="hidden" name="bid[0].UserId" value="" />
<input type="hidden" name="bid[0].CompanyId" value="" />
#Html.DropDownList("bid[0].PositionId", (IEnumerable<SelectListItem>)ViewBag.SelectList, htmlAttributes: new { #class = "form-control dlist" })
</td>
<td>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="bid[0].BidAmount" />
<span class="input-group-addon ">.00</span>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-default">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Jquery:
$(document).ready(function () {
$i = 0;
var bid = $("#form-table");
var dlist = $(".dlist").clone().attr("name", "bid[" + $i + "].PositionId");
$("#add").click(function () {
$i++;
var id = '<input type="hidden" name="bid[' + $i + '].Id"/>';
var userId = '<input type="hidden" name="bid[' + $i + '].UserId"/>';
var companyId = '<input type="hidden" name="bid[' + $i + '].CompanyId"/>';
var bidAmount = '<div class="input-group"><span class="input-group-addon">$</span><input type="text" class="form-control" name="bid[' + $i + '].BidAmount"/></div>';
bid.append("<tr><td id='mvc" + $i +"'>" + id + userId + companyId + "</td><td> " + bidAmount + " </td></tr>");
$("#mvc" + $i + "").append(dlist.clone());
});
$("#remove").click(function () {
if ($("#form-table tr").length > 2) {
$i--;
$("#form-table tr:last").remove();
} else {
return;
}
});
});
Your using the name bid but your controller is expecting bids. Try making the parameter name for the action bid (or vice versa) and run it again.

Linq query foreach element in array

I have a Controller with an ActionResult which gets three arrays from the view at HttpPost.
The arrays are the Id(tableId) the position from the top(positionY) and the position from the left(positionX).
When you click save the ActionResult needs to update all the Positions from the corresponding id's in the database.
This is my Controller:
private BonTempsDbContext db = new BonTempsDbContext();
[HttpPost]
public ActionResult Index(int[] tableId, int[] tablePosX, int[] tablePosY)
{
int i = 0;
foreach (var id in tableId)
{
int number = tableId[i];
Tafel tafel = db.Tafel
.Where(x => x.id == number)
.ToList();
db.Entry(tafel).State = EntityState.Modified;
i++;
}
return View(db.Tafel.ToList());
}
I get the error:
Cannot implicitly convert type
'System.Collections.Generic.List' to
'BonTempsMVC.Tafel'
This is my View if you van get something usefull out of it.
#model IEnumerable<BonTempsMVC.Tafel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div class="VoegToeBtn">
<a href="/tafel/create">
<span class="btn btn-default">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Maak nieuw menu aan
</span>
</a>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="tablewrapper">
#foreach (var item in Model)
{
var positionXId = "posX" + item.id;
var positionYId = "posY" + item.id;
<div class="draggable ui-widget-content" id="#Html.DisplayFor(ModelItem => item.id)">
<input type="text" hidden name="tableId" value="#Html.DisplayFor(ModelItem => item.id)" />
<input type="text" hidden name="tablePosX" id="#positionXId" value="" />
<input type="text" hidden name="tablePosY" id="#positionXId" value="" />
<p>#Html.DisplayFor(ModelItem => item.tafelNaam)</p>
</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>
}
<script>
$(".draggable").draggable({
snap: ".draggable",
snapMode: "outer",
stop: function (event, ui) {
var finalOffset = $(this).offset();
var finalxPos = finalOffset.left;
var finalyPos = finalOffset.top;
var itemId = $(this).attr('id');
var posXid = "posX" + itemId;
var posYid = "posY" + itemId;
$('input:text[id="' + posXid + '"]').attr("value", finalxPos);
$('input:text[id="' + posYid + '"]').attr("value", finalyPos);
},
});
</script>
And tafel model:
namespace BonTempsMVC
{
public class Tafel
{
public int id { get; set; }
public string tafelNaam { get; set; }
public bool beschikbaar { get; set; }
public float positionY { get; set; }
public float positionX { get; set; }
}
}
Try this:-
List<Tafel> tafel = db.Tafel
.Where(x => x.id == number)
.ToList();
Here, List<Tafel> is returned but you are storing that in Tafel object. If you are pretty sure that in Tafel entity there will be only one item with matching id then do this:-
Tafel tafel = db.Tafel.FirstOrDefault(x => x.id == number);
As, suggested by #DavidG you can also do this:-
Tafel tafel = db.Tafel.Find(number);

Categories

Resources