I want to display dropdownlist in Bootstrap Modal When I click on button add it displays this error ( Server Error in '/' Application. There is no ViewData item of type 'IEnumerable' that has the key 'DepartmentId'.)
it returns the NULL value someone help me to solve this problem
In Controller:
Database1Entities db = new Database1Entities();
public ActionResult Index()
{
List<Department> DeptList = db.Departments.ToList();
ViewBag.ListOfDepartment = new SelectList(DeptList, "DepartmentId", "DepartmentName");
return View();
}
public ActionResult GetStudent()
{
List<StudentViewModel> data = db.Students.Select(x => new StudentViewModel
{
StudentId =x.StudentId,
FirstName = x.FirstName,
LastName = x.LastName,
DepartmentName = x.Department.DepartmentName,
}).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
public ActionResult GetStudentPartial(int? id)
{
var student = db.Students.Find(id) ?? new Student();
return PartialView("_CreateOrUpdateStudentPartial", student);
}
public ActionResult CreateOrUpdateStudent(Student student)
{
if (ModelState.IsValid)
{
if (student.StudentId > 0)
{
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
}
else
{
db.Students.Add(student);
}
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json(false, JsonRequestBehavior.AllowGet);
}
public ActionResult Delete(int id)
{
try
{
var student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
Partial View:
#model Example1.Models.Student
<form name="studentForm">
<div class="modal-header">
<h5 class="modal-title">
Modal title
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</h5>
</div>
<div class="modal-body">
#Html.HiddenFor(x => x.StudentId)
<div class="row">
<div class="col-md-12">
<div class="col-md-6">
<div class="form-group">
<label>First Name</label>
#Html.EditorFor(x => x.FirstName, new { htmlAttributes = new { #class = "form-control", #placeholder = "First Name*", Required = true } })
#Html.ValidationMessageFor(x => x.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Last Name</label>
#Html.EditorFor(x => x.LastName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Last Name*", Required = true } })
#Html.ValidationMessageFor(x => x.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Department Name</label>
#Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { #id = "DropDwn", #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm pull-left" data-dismiss="modal">Cancel</button>
<button type="button" onclick="createOrUpdate()" class="btn btn-success pull-left">Save</button>
</div>
</form>
View:
<div style="width:90%; margin:0 auto" class="tablecontainer">
<p><button type="button" class="btn btn-sm btn-success" onclick="getStudent()">Add New Student</button></p>
<table id="myDatatable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>DepartmentName</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" role="dialog" id="studentModal" aria-labelledby="studentModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="studentmodalBody">
</div>
</div>
</div>
Script:
<script>
var datatable;
$(document).ready(function () {
datatable = $('#myDatatable').DataTable({
"ajax": {
"url": '/home/GetStudent',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "FirstName", "autoWidth": true },
{ "data": "LastName", "autoWidth": true },
{
"data": "DepartmentName", "render": function (data) {
return data;
}
},
{
"data": "StudentId", "width": "50px", "render": function (data) {
return '<button class="btn btn-success" onclick="getStudent(' + data + ')">Edit</button>';
}
},
{
"data": "StudentId", "width": "50px", "render": function (data) {
return '<button class="btn btn-danger" onclick="Delete(' + data + ')">Delete</button>';
}
},
]
})
})
function getStudent(id) {
$.get("/Home/GetStudentPartial", { id: id }, function (res) {
$("#studentmodalBody").html(res);
$("#studentModal").modal('show');
})
}
function createOrUpdate() {
var modal = $("#studentModal");
var form = $('form[name= "studentForm"]');
form.validate();
if (!form.valid()) {
return;
} else {
var data = form.serialize();
$.post("/home/CreateOrUpdateStudent", data, function (res) {
if (res) {
modal.modal('hide');
datatable.ajax.reload();
}
})
}
}
function Delete(id) {
if (confirm("Are you sure ? ") == true) {
$.get("/Home/Delete", { id: id }, function (res) {
if (res) {
datatable().ajax.reload();
}
})
}
}
</script>
If your DeptList is not null, try change code below :
#Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { #id = "DropDwn", #class = "form-control" })
to:
#Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as IEnumerable<SelectListItem>, "--Select Dept--", new { #id = "DropDwn", #class = "form-control" })
EDIT: I've just realized that you are filling your ViewBag in the Index() method but your are calling it in _CreateOrUpdateStudentPartial and you can't do that. ViewBag is not tranffering data between views.
public ActionResult GetStudentPartial(int? id)
{
var student = db.Students.Find(id) ?? new Student();
// you need to add here
List<Department> DeptList = db.Departments.ToList();
ViewBag.ListOfDepartment = new SelectList(DeptList,"DepartmentId","DepartmentName");
return PartialView("_CreateOrUpdateStudentPartial", student);
}
Related
I am trying to populate/fill a dropdown but I can't seem to get the values I need.
The "Employee Name" dropdown does not get populated while the "Platform Group" one does.
For "Employee Name" I use POST because this method is called by another VIEW in the software so I'd rather not change it.
I tried everything I could but the values will not show in the console or in the UI.
What am I missing?
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FXM.BO.ViewModels
{
public class NewAffiliateViewModel
{
public NewAffiliateViewModel()
{
}
public int Id { get; set; }
public string AffiliateName { get; set; }
public string Email { get; set; }
public int Employee { get; set; }
public int MT4Group { get; set; }
}
}
View
#model FXM.BO.ViewModels.NewAffiliateViewModel
#{
ViewBag.Title = "CreateAffiliate";
Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
}
<h2>Create Affiliate</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4 class="hidden">NewAffiliateViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AffiliateName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AffiliateName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AffiliateName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.Employee, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee, "", new { #class = "text-danger" })
</div>
</div>*#
#*<div class="form-group">
#Html.LabelFor(model => model.MT4Group, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MT4Group, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MT4Group, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("employeeName") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-10 ">
#Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-10 ">
#Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option2"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("platform_group_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
#*Create button*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>
#*<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>*#
<script type="text/javascript">
// document.ready function
$(function () {
refreshGroups();
// selector has to be . for a class name and # for an ID
$('#create-affiliate-button').click(function (e) {
//e.preventDefault(); // prevent form from reloading page
console.log("blahblahblah");
var b = $("form").serialize();
//var a = $("form").serializeArray();
console.log("formvalues", b);
$.ajax({
url: "/en/AjaxUI/CreateAffiliate",
type: "GET",
dataType: "json",
data: b,
},
//error: function (jqXHR, exception) {
// failMessage();
//}
});
});
});
function refreshGroups() {
var pltf = "MT4_LIVE";
var out = $('#MT4Group');
if (pltf != null && pltf !== "") {
$.ajax({
url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
data: {
platform: pltf, currency: "", withId : true
},
type: 'GET',
beforeSend: function () {
$('#tpLoader').show();
},
complete: function () {
$('#tpLoader').hide();
},
success: function (data) {
populateDropDown(out, data);
//$('#recomandedGroup').show();
}
});
} else {
out.empty();
out.append($('<option></option>').val('').html(window.defaultSelection));
}
}
//GetEmployeesExcept - Method that populates the Dropdown for EmployeeName
$(function() {
$.validator.addMethod("regxPhone", function(value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function(value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function(value, element, param) {
return valiEmailAjax($("#Email").val());
});
$('#create-affiliate-button').select2({
theme: "bootstrap",
ajax: {
url: "/en/BOEmployeeAjax/GetEmployeesExcept",
type: "POST",
dataType: "json",
data: function(params) {
return {
emplId: 0,
t: params.term
}
},
processResults: function(data, params) {
return { results: data }
}
},
placeholder: window.selectAnotherSupervisor,
escapeMarkup: function(markup) { return markup; },
minimumInputLength: 0
});
</script>
Method in the Controller (for Employee Name)
[HttpPost]
[OutputCache(CacheProfile = "Cache10mn", Location = OutputCacheLocation.Client, NoStore = true)]
public JsonResult GetEmployeesExcept(int emplId, string t, bool searchByUserId=false)
{
t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
if (!searchByUserId)
{
return Json(CrmServices.GetAllEmployees()
.Where(w => w.Id != emplId && string.Format("{1}{0}", w.UserDetails.Fullname, w.Id).ToLower().Contains(t.ToLower()))
.Select(s => new { id = s.Id, text = string.Format("{1} : {0}", s.UserDetails.Fullname, s.Id) }));
}
else
{
return Json(CrmServices.GetAllEmployees()
.Where(w => w.UserDetails != null && int.Parse(w.UserDetails.UserID) != emplId && string.Format("{1}{0}", w.UserDetails.Fullname, w.UserDetails.UserID).ToLower().Contains(t.ToLower()))
.Select(s => new { id = s.UserDetails.UserID, text = string.Format("{1} : {0}", s.UserDetails.Fullname, s.UserDetails.UserID) }));
}
}
method in the Controller (for "Platform Group")
public JsonResult CreateAffiliate(NewAffiliateViewModel newAffiliateViewModel)
{
try
{
var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
//SystemServices.ResendEmail(userId);
return Json("success");
//return Json(null, JsonRequestBehavior.DenyGet);
}
catch (Exception e)
{
throw e;
}
}
Also, when I uncomment the code for the ajax request for "Employee Name", the "Platform group" stops being populated. When I comment it back, the "Platform group" is populated just fine.
Thank you for any response.
You need to search for : "Select2"
Here is site https://select2.org/
Read the guid, its easy
UPDATE 1:
Here is EXAMPLE of code, that you need, man.
I have this Razor dropdown that gets the info from the DB via ajax but the options that show on the dropdown don't get selected. How to make the dropdown options become selected on click?
I tried to implement the answer to a similar question but it didn't work:
select2 load data using ajax cannot select any option
This is what I have so far:
Ajax
$(document).ready(function () {
$.validator.addMethod("regxPhone", function (value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function (value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function (value, element, param) {
return valiEmailAjax($("#Email").val());
});
$('#dropdown-employees').select2({
minimumInputLength: 0,
multiple: false,
dropdownParent: $('#dropdown-email-for-select2'),
ajax: {
url: "/en/BOEmployeeAjax/GetEmployeesExcept",
type: "POST",
dataType: "json",
data: function (params) {
return {
emplId: 0,
t: params.term
}
},
processResults: function (data, params) {
return { results: data }
}
},
placeholder: window.selectAnotherSupervisor,
escapeMarkup: function (markup) { return markup; },
});
Razor dropdown
<div class="col-md-4 fieldSize4" id="dropdown-employees">
#Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
Code after 1st changes:
#model FXM.BO.ViewModels.NewAffiliateViewModel
#{
ViewBag.Title = "CreateAffiliate";
Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
}
<h2>Create Affiliate</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4 class="hidden">NewAffiliateViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AffiliateName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AffiliateName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AffiliateName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="dropdown-email-for-select2">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.Employee, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee, "", new { #class = "text-danger" })
</div>
</div>*#
#*<div class="form-group">
#Html.LabelFor(model => model.MT4Group, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MT4Group, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MT4Group, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("employeeName") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-4 fieldSize4" id="dropdown-employees">
#Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
#*<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />*#
</div>
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-4 fieldSize4">
#Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option2"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("platform_group_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
#*Create button*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
</div>
</div>
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// document.ready function
$(function () {
refreshGroups();
// selector has to be . for a class name and # for an ID
$('#create-affiliate-button').click(function (e) {
//e.preventDefault(); // prevent form from reloading page
console.log("blahblahblah");
//alert("hiii");
var b = $("form").serialize();
//var a = $("form").serializeArray();
console.log("formvalues", b);
$.ajax({
url: "#Url.Action("CreateAffiliate", "AjaxUI")",
type: "GET",
dataType: "json",
data: {
newAffiliateViewModel : b
},
//error: function (jqXHR, exception) {
// failMessage();
//}
});
});
});
function refreshGroups() {
var pltf = "MT4_LIVE";
var out = $('#MT4Group');
if (pltf != null && pltf !== "") {
$.ajax({
url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
data: {
platform: pltf, currency: "", withId : true
},
type: 'GET',
beforeSend: function () {
$('#tpLoader').show();
},
complete: function () {
$('#tpLoader').hide();
},
success: function (data) {
populateDropDown(out, data);
//$('#recomandedGroup').show();
}
});
} else {
out.empty();
out.append($('<option></option>').val('').html(window.defaultSelection));
}
}
//GetEmployeesExcept - Method that populates the Dropdown for EmployeeName
$(document).ready(function () {
$.validator.addMethod("regxPhone", function (value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function (value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function (value, element, param) {
return valiEmailAjax($("#Email").val());
});
var WithId = $('#dropdown-employees');
if(WithId.length>0){
var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
var $ajax = WithId;
loadSelectData();
}
});
function loadSelectData() {
var cstoken = $('input[name="_token"]').val();
$ajax.select2({
ajax: {
url: ajax_url,
dataType: 'json',
data: function (params, cstoken, page) {
return {
"_token": cstoken,
searchtxt: params.term, // search term
page: params.page
};
},
processResults: function (data) {
var vh = [];
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value) {
var itemName = value.empname;
var itemId = value.id;
vh.push({id: itemId, text: itemName });
});
console.log(vh);
return {
results: vh,
pagination: {
more: true
}
}
},
placeholder: 'Search for a result',
minimumInputLength: 1,
}
});
}
</script>
Please change your select2 ajax code like.
Please change your select2 ajax code like.
$(document).ready(function () {
$.validator.addMethod("regxPhone", function (value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function (value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function (value, element, param) {
return valiEmailAjax($("#Email").val());
});
var WithId = $('#dropdown-employees');
if(WithId.length>0){
var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
var $ajax = WithId;
loadSelectData();
}
});
function loadSelectData() {
var cstoken = $('input[name="_token"]').val();
$ajax.select2({
ajax: {
url: ajax_url,
dataType: 'json',
data: function (params, cstoken, page) {
return {
"_token": cstoken,
searchtxt: params.term, // search term
page: params.page
};
},
processResults: function (data) {
var vh = [];
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value) {
var itemName = value.empname;
var itemId = value.id;
vh.push({id: itemId, text: itemName });
});
console.log(vh);
return {
results: vh,
pagination: {
more: true
}
}
},
placeholder: 'Search for a result',
minimumInputLength: 1,
}
});
}
Good day! I just want to know how to add/sum all the values in a specific database column based on their inputted in a textbox StartDate and EndDate? Textbox "daysworked" only shows the sum according to the sum of the value and EmployeeId but not according to the StartDate and EndDate. I want to display the sum of a specific database column according to their EmployeeId, StartDate and EndDate.
This is my View where I created script that will post my sum and employeeid.
#using PayrollWeb.Models
#model PayrollWeb.Models.PayrollFormModel
#{
ViewBag.Title = "AddOrEdit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("AddOrEdit", "Payroll", FormMethod.Post, new { onsubmit = "return SubmitFormPayroll(this)" }))
{
#Html.HiddenFor(model => model.Id)
<h1 style="text-align: center;"><span class="fa fa-calculator"></span> Payroll</h1>
<br />
<div class="panel-group col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
Employee Details
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.EmployeeId, new { #class = "form-label" })
#Html.DropDownListFor(x => x.EmployeeId, Model.Employees, "", new { #class = "form-control" , #id="employeeid"})
#Html.ValidationMessageFor(x => x.EmployeeId, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.StartDate, new { #class = "form-label" })
#Html.TextBoxFor(x => x.StartDate, new { #class = "form-control", #id = "startdate", #type = "date" })
#Html.ValidationMessageFor(x => x.StartDate, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.EndDate, new { #class = "form-label" })
#Html.TextBoxFor(x => x.EndDate, new { #class = "form-control", #id = "enddate", #type = "date" })
#Html.ValidationMessageFor(x => x.EndDate, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.PayDate, new { #class = "form-label" })
#Html.TextBoxFor(x => x.PayDate, new { #class = "form-control", #id = "datepickertodin", #type = "date" })
#Html.ValidationMessageFor(x => x.PayDate, null, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.PayFrequency, new { #class = "form-label" })
#Html.TextBoxFor(x => x.PayFrequency, new { #class = "form-control", #Value = "BI-WEEKLY", #readonly = "readonly" })
#Html.ValidationMessageFor(x => x.PayFrequency, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.DaysWorked, new { #class = "form-label" })
#Html.TextBoxFor(x => x.DaysWorked, new { #class = "form-control", #id="daysworked" })
#Html.ValidationMessageFor(x => x.DaysWorked, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<div class="form-group">
#Html.LabelFor(x => x.MonthlyRate, new { #class = "form-label" })
#Html.TextBoxFor(x => x.MonthlyRate , new { #class = "form-control", #id="monthlyrate"})
#Html.ValidationMessageFor(x => x.MonthlyRate, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(x => x.SalaryPerDay, new { #class = "form-label" })
#Html.TextBoxFor(x => x.SalaryPerDay, new { #class = "form-control", #id = "salaryperday" })
</div>
<div class="form-group">
#Html.LabelFor(x => x.WorkDays, new { #class = "form-label" })
#Html.TextBoxFor(x => x.WorkDays, new { #class = "form-control", #id = "workdays" })
</div>*#
<div class="panel-group col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
Income
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(x => x.BasicPayAmount, new { #class = "form-label" })
#Html.TextBoxFor(x => x.BasicPayAmount, new { #class = "form-control", #id = "basicpayamount" })
#Html.ValidationMessageFor(x => x.BasicPayAmount, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
</div>
<div class="panel-group col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
Deductions
</div>
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(x => x.WitholdingTax, new { #class = "form-label" })
#Html.TextBoxFor(x => x.WitholdingTax, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.WitholdingTax, null, new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(x => x.PagibigContribution, new { #class = "form-label" })
#Html.TextBoxFor(x => x.PagibigContribution, new { #class = "form-control", #Value = "100.00", #readonly = "readonly" })
#Html.ValidationMessageFor(x => x.PagibigContribution, null, new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(x => x.PhilhealthContribution, new { #class = "form-label" })
#Html.TextBoxFor(x => x.PhilhealthContribution, new { #class = "form-control", #Value = "191.25", #readonly = "readonly" })
#Html.ValidationMessageFor(x => x.PhilhealthContribution, null, new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(x => x.SSSContribution, new { #class = "form-label" })
#Html.TextBoxFor(x => x.SSSContribution, new { #class = "form-control", #Value = "560.00", #readonly = "readonly" })
#Html.ValidationMessageFor(x => x.SSSContribution, null, new { #class = "text-danger" })
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(x => x.Deduction, new { #class = "form-label" })
#Html.TextBoxFor(x => x.Deduction, new { #class = "form-control", #id = "deduction" })
#Html.ValidationMessageFor(x => x.Deduction, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<input id="btnAdd" type="button" value="Add" onclick="AddTextBox()" class="btn btn-info" style="margin-top: 25px;" />
</div>
</div>
<div id="TextBoxContainer" style="margin-top: 6%; ">
<!--Textboxes will be added here -->
</div>
<br />
<div class="form-group">
#Html.LabelFor(x => x.CashLoan, new { #class = "form-label" })
#Html.TextBoxFor(x => x.CashLoan, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.CashLoan, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="panel-group col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
Summary
</div>
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(x => x.TotalSalary, new { #class = "form-label" })
#Html.TextBoxFor(x => x.TotalSalary, new { #class = "form-control", #id = "totalsalary" })
#Html.ValidationMessageFor(x => x.TotalSalary, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-2"></div>
<div class="col-md-2">
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-primary" />
</div>
</div>
</div>
<span class="fa fa-backward"></span> Back to Dashboard
<script type="text/javascript">
function GetDynamicTextBox(value) {
var div = $("<div />").attr("class", "row").attr("style","margin-top: 6px;");
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("style", "width:30%;margin-left:5%;");
textBox.val(value);
div.append(textBox);
var textBox1 = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox1").attr("style", "width:30%;margin-left:5%;");
textBox1.val(value);
div.append(textBox1);
var button = $("<input />").attr("type", "button").attr("value", "Remove").attr("style", "width:20%;margin-left:5%;");
button.attr("onclick", "RemoveTextBox(this)");
div.append(button);
return div;
}
function AddTextBox() {
var div = GetDynamicTextBox("");
$("#TextBoxContainer").append(div);
}
function RemoveTextBox(button) {
$(button).parent().remove();
}
$('#employeeid').change( function () {
var employeeid = $(this).val();
//var startdatedata = $('#startdate').val();
//var enddatedata = $('#enddate').val();
$.ajax({
type: 'POST',
url: "#Url.Action("LoadDetails", "Payroll")",
data: {
employeeid: employeeid,
//startdatedata: startdatedata,
//enddatedata: enddatedata
},
dataType: 'json',
success: function (data) {
$('#employeeid').val(data.EmployeeId);
//$('#startdate').val(data.StartDate);
//$('#enddate').val(data.EndDate);
$('#daysworked').val(data.DaysWorked);
}
});
});
#*$(function () {
var values = eval('#Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function () {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});*#
//$(function () {
// $('#datepickerto').datepicker({ //datepicker startdate
// dateFormat: "yy/mm/dd",
// changeMonth: true,
// changeYear: true,
// showOn: "both",
// buttonText : "<i class='fa fa-calendar'></i>"
// });
//});
//$(function () {
// $('#datepickertodin').datepicker({ //datepicker enddate
// dateFormat: "yy/mm/dd",
// changeMonth: true,
// changeYear: true,
// showOn: "both",
// buttonText: "<i class='fa fa-calendar'></i>"
// });
//});
//$(function () { //calculate
// $("#salaryperday,#workdays,#deduction").keyup(function (e) {
// var salary = $("#salaryperday").val();
// var work = $("#workdays").val();
// var deduction = $("#deduction").val();
// var result = "";
// if (salary !== "" && work !== "" && deduction !== "" && $.isNumeric(salary) && $.isNumeric(work) && $.isNumeric(deduction)) {
// result = parseFloat(salary) * parseFloat(work) - parseFloat(deduction);
// }
// $("#totalsalary").val(result);
// });
//});
$(function () { //calculate
$("#monthlyrate").keyup(function (e) {
var monthlyrate = $("#monthlyrate").val();
var result = "";
if (monthlyrate !== "" && $.isNumeric(monthlyrate)) {
result = parseFloat(monthlyrate) / 2;
}
$("#basicpayamount").val(result);
});
});
</script>
}
And this is my PayrollController where I have my LoadDetails function where my linq.
using PayrollWeb.DB.Core;
using PayrollWeb.DB.Data;
using PayrollWeb.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace PayrollWeb.Controllers
{
public class PayrollController : Controller
{
// GET: Payroll
private PayrollwebContext db = new PayrollwebContext(); //connection
public ActionResult Index()
{
return View();
}
public JsonResult GetData()
{
var payrolls = (from p in db.Payrolls.ToList()
join e in db.Employees.ToList() on p.EmployeeId equals e.Id
select new PayrollListModel
{
Id = p.Id,
EmployeeName = e.FirstName + " " + e.MiddleName + " " + e.LastName,
StartDate = Convert.ToDateTime(p.StartDate),
EndDate = Convert.ToDateTime(p.EndDate),
Deduction = p.Deduction,
TotalSalary = p.TotalSalary
});
return Json(new { data = payrolls.ToList() }, JsonRequestBehavior.AllowGet);
}
public ActionResult AddOrEdit(int? id)
{
var model = new PayrollFormModel();
if (id != null)
model.Id = Convert.ToInt32(id);
model = PreparePayrollFormModel(model);
return View(model);
}
//[Authorize(Roles = "Admin")]
[HttpPost]
public ActionResult AddOrEdit(PayrollFormModel model, string[] DynamicTextBox, int[] DynamicTextBox1)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.Values = serializer.Serialize(DynamicTextBox);
ViewBag.Values = serializer.Serialize(DynamicTextBox1);
//bool returnloop = false;
//foreach (string textboxValue in DynamicTextBox) //category
//{
//foreach (int textboxValue1 in DynamicTextBox1) //amount
//{
using (var db = new PayrollwebContext())
{
if (model.Id > 0)
{ // update
var EmployeePayroll = db.Payrolls.FirstOrDefault(x => x.Id == model.Id);
EmployeePayroll.Id = model.Id;
EmployeePayroll.EmployeeId = (int)model.EmployeeId;
EmployeePayroll.StartDate = model.StartDate;
EmployeePayroll.EndDate = model.EndDate;
EmployeePayroll.PayFrequency = model.PayFrequency;
EmployeePayroll.PayDate = model.PayDate;
EmployeePayroll.DaysWorked = model.DaysWorked;
EmployeePayroll.MonthlyRate = model.MonthlyRate;
EmployeePayroll.WitholdingTax = model.WitholdingTax;
EmployeePayroll.PagibigContribution = model.PagibigContribution;
EmployeePayroll.PhilhealthContribution = model.PhilhealthContribution;
EmployeePayroll.SSSContribution = model.SSSContribution;
//EmployeePayroll.SalaryPerDay = model.SalaryPerDay;
//EmployeePayroll.WorkDays = model.WorkDays;
EmployeePayroll.Deduction = model.Deduction;
EmployeePayroll.CashLoan = model.CashLoan;
EmployeePayroll.TotalSalary = model.TotalSalary;
db.Payrolls.AddOrUpdate(EmployeePayroll);
db.SaveChanges();
return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
}
else
{ //insertion
var payrolls = new Payroll
{
EmployeeId = (int)model.EmployeeId,
StartDate = model.StartDate,
EndDate = model.EndDate,
PayFrequency = model.PayFrequency,
PayDate = model.PayDate,
DaysWorked = model.DaysWorked,
MonthlyRate = model.MonthlyRate,
BasicPayAmount = model.BasicPayAmount,
WitholdingTax = model.WitholdingTax,
PagibigContribution = model.PagibigContribution,
PhilhealthContribution = model.PhilhealthContribution,
SSSContribution = model.SSSContribution,
//SalaryPerDay = model.SalaryPerDay,
//WorkDays = model.WorkDays,
Deduction = model.Deduction,
CashLoan = model.CashLoan,
TotalSalary = model.TotalSalary
};
db.Payrolls.Add(payrolls);
List<Deductions> list = new List<Deductions>();
for (int i = 0; i < DynamicTextBox.Length; i++)
{
var deduct = new Deductions
{
EmployeeId = (int)payrolls.EmployeeId,
Category = DynamicTextBox[i],
Amount = Convert.ToInt32(DynamicTextBox1[i]),
};
list.Add(deduct);
}
db.Deductionss.AddRange(list);
db.SaveChanges();
//return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
}
model = PreparePayrollFormModel(model);
return View(model);
}
public PayrollFormModel PreparePayrollFormModel(PayrollFormModel model) //model null
{
model.Employees = db.Employees.Select(x => new SelectListItem //laman ng dropdown
{
Text = x.FirstName + " " + x.MiddleName + " " + x.LastName,
Value = x.Id.ToString()
});
if (model.Id > 0) //edit din to para magreturn ng value
{
var payroll = db.Payrolls.Find(model.Id); //null
model.EmployeeId = payroll.EmployeeId;
model.StartDate = payroll.StartDate;
model.EndDate = payroll.EndDate;
//model.SalaryPerDay = payroll.SalaryPerDay;
//model.WorkDays = payroll.WorkDays;
model.Deduction = payroll.Deduction;
model.TotalSalary = payroll.TotalSalary;
model.Employees = db.Employees.Select(x => new SelectListItem //laman ng dropdown
{
Text = x.FirstName + " " + x.MiddleName + " " + x.LastName,
Value = x.Id.ToString()
});
}
return model;
}
[HttpPost]
public ActionResult Delete(PayrollFormModel model)
{
if (model.Id > 0)
{
var orders = db.Payrolls.FirstOrDefault(x => x.Id == model.Id);
db.Payrolls.Remove(orders);
db.SaveChanges();
return Json(new { success = true, message = "Deleted Successfully" }, JsonRequestBehavior.AllowGet);
}
return View(model);
}
public ActionResult LoadDetails(int employeeid, DateTime? startdatedata, DateTime? enddatedata)
{
//var getEmployee = db.Employees.FirstOrDefault(x => x.Id == employeeid); // nakuha ko na dito yung id ni customer
//var getAttendace = db.Attendances.FirstOrDefault(x => x.EmployeeId == getEmployee.Id);
//var getPayroll = db.Payrolls.FirstOrDefault(x => x.EmployeeId == employeeid);
//example lang to aa depende sayo kung decimal ba or int or var
decimal? sum = db.Attendances
.Where(x => x.EmployeeId == employeeid)
//&& x.Date >= startdatedata &&
//x.Date <= enddatedata)
.Sum(x => x.Overtime);
var LoadDetails = new PayrollFormModel
{
EmployeeId = employeeid,
//StartDate = startdatedata,
//EndDate = enddatedata,
DaysWorked = sum,
};
return Json(LoadDetails, JsonRequestBehavior.AllowGet);
}
}
}
I hope someone will help me. Thank you in advance. Have a great day!
var sum = db.Attendances.Where(x => x.EmployeeId == employeeid && x.Date >= startdatedata && x.Date <= enddatedata).Sum(y => y.Overtime)
Should be fine. If there are any error try .Where().ToList().Sum()
I already figure out what's wrong with my code. I'll just change this
decimal? sum = db.Attendances
.Where(x => x.EmployeeId == employeeid)
//&& x.Date >= startdatedata &&
//x.Date <= enddatedata)
.Sum(x => x.Overtime);
to this:
decimal? sum = db.Attendances
.Where(x => x.Date >= startdatedata &&
x.Date <= enddatedata && x.EmployeeId == employeeid)
.Sum(x => x.Overtime);
Thank you!
I have a table on which there's an Edit button for every record at the last column.
My goal is to have an editable form on a modal for the record on which the user pressed the Edit button.
In order to accomplish that, I've created a Partial View which i want to be loaded on the modal, but after tons of tries, i cannot get it working. The JS created to compose the partial view URL and loading into the modal seems to have no effect and it's raising the following error:
VM364 ESa31501901:361 Uncaught ReferenceError: ESa31501901 is not
defined
at HTMLAnchorElement.onclick
Note: ESa31501901 is the first parameter passed into the JS function.
This is my intention:
a) Edit() : This method will return all records.
b) EditClientFeature(string ClientID, string WorkProcessID): This method will return a partial view containing the record of a particular client. This method is called when we start editing a client record. The client record is displayed in modal (popup).
c) EditClientFeature(ClientFeatureViewModel model): This method will update the client record.
ClientFeature ViewModel
public class ClientFeatureViewModel
{
public string ClientID { get; set; }
public string WorkProcessID { get; set; }
public int? Certification { get; set; }
public bool? TrackingActive { get; set; }
public string ClientCode { get; set; }
public string ContractNo { get; set; }
public string ProductCode { get; set; }
}
Edit.cshtml
[...]
<tbody>
#foreach (var feature in Model.ClientFeatures)
{
<tr>
<td style="text-align:center"><strong>#feature.WorkProcessId</strong>/td>
<td style="text-align:center">#feature.Certificate</td>
<td style="text-align:center">#feature.TrackingActive</td>
<td style="text-align:center">#feature.ClientCode</td>
<td style="text-align:center">#feature.ContractNo</td>
<td style="text-align:center">#feature.ProductCode</td>
<td>
<i class="glyphicon glyphicon-pencil"></i>
</td>
</tr>
}
</tbody>
[...]
<div class="modal fade" id="ModalClientFeatures">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Edit</h3>
</div>
<div class="modal-body" id="ModalBodyDiv">
<!-- Here's where i want to show the partial view-->
</div>
</div>
</div>
</div>
[...]
<script>
function EditCF(ClientID, WorkProcessID) {
var url = "/Admin/EditClientFeature?ClientID=" + ClientID + "?WorkProcessID=" + WorkProcessID;
$("#ModalBodyDiv").load(url, function () {
$("#ModalClientFeatures").modal("show");
})
}
</script>
ClientFeaturepartialView.cshtml
#model Project.Models.ClientFeatureViewModel
<script src="~/Scripts/jquery-3.3.1.js"></script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form id="myForm">
<div class="form-horizontal">
<h4>ClientFeatureViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ClientID)
<div class="form-group">
#Html.LabelFor(model => model.WorkProcessID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.WorkProcessID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WorkProcessID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Certification, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Certification, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Certification, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TrackingActive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.TrackingActive)
#Html.ValidationMessageFor(model => model.TrackingActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClientCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClientCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClientCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContractNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContractNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContractNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
<a href="#" id="btnSubmit" class="btn btn-success btn-block">
<span>Update</span>
</a>
</div>
</div>
</div>
</form>
}
Controller
public ActionResult EditClientFeature(string ClientID, string WorkProcessID)
{
PMEntities db = new EntityConn().Db;
ClientFeatures ClientFeature = db.ClientFeatures.Where(cf => cf.ClientId == ClientID && cf.WorkProcessId == WorkProcessID).SingleOrDefault();
if (ClientFeature != null) {
ClientFeatureViewModel model = new ClientFeatureViewModel
{
ClientID = ClientFeature.ClientId,
WorkProcessID = ClientFeature.WorkProcessId,
Certification = ClientFeature.Certificate,
TrackingActive = ClientFeature.TrackingActive,
ClientCode = ClientFeature.ClientCode,
ContractNo = ClientFeature.ContractNo,
ProductCode = ClientFeature.ProductCode,
};
return PartialView("ClientFeaturePartialView", model);
}
else { return View("Error"); }
}
[HttpPost]
public ActionResult EditClientFeature(ClientFeatureViewModel model)
{
try
{
PMEntities db = new EntityConn().Db;
if (model.ClientID != null)
{
//update
ClientFeatures ClientFeature = db.ClientFeatures.Where(cf => cf.ClientId == model.ClientID && cf.WorkProcessId == model.WorkProcessID).SingleOrDefault();
ClientFeature.Certificate = model.Certification;
ClientFeature.ClientCode = model.ClientCode;
ClientFeature.ContractNo = model.ContractNo;
ClientFeature.ProductCode = model.ProductCode;
ClientFeature.TrackingActive = model.TrackingActive;
db.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
I think your onclick function parameter value is treated as a variable, not a string.
Solution 1:
Try below to pass as string: (Not tested though!)
onclick="EditCF(\'' + #Model.Piva + '\', \'' + #feature.WorkProcessId+ '\')"
Solution 2:
It's best to Attach a click handler after adding a class for your link. And use HTML5 data attributes for storing your value client side.
<i class="glyphicon glyphicon-pencil"></i>
$('.editClient).on('click', function() {
var clientID = $(this).data('ClientID');
var workProcessId = $(this).data('WorkProcessId');
var url = "/Admin/EditClientFeature?ClientID=" + clientID
+ "?WorkProcessID=" + workProcessID;
$("#ModalBodyDiv").load(url, function () {
$("#ModalClientFeatures").modal("show");
})
});
Reference
Hope this helps.
I'm using VS2013 Asp.Net MVC 5 with Stimulsoft Report 2013.5
It's ok, But the following javascript exception on View:
marginsPx[i].replace is not a function
My View:
<div class="#Model.ReportParametersVisibilityCssClass">
#using (Html.BeginForm("Kardex", "KaraReports", FormMethod.Post, new Dictionary<string, object> { { "id", "ReportForm" }, { "class", "form-horizontal" }, { "role", "form" } }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.SelectedEmployeesEmpNoInJsonFormat)
#Html.HiddenFor(model => model.SelectedEmployeesFiltering)
#Html.HiddenFor(model => model.StartDate)
#Html.HiddenFor(model => model.EndDate)
#Html.HiddenFor(model => model.Month)
<div class="maxwidth500 center-block">
<div class="form-group">
#Html.Action("MonthSelector", "CommonActions", new { month = Model.Month, startDate = Model.StartDate, endDate = Model.EndDate })
</div>
<hr />
<div class="form-group">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<button type="button" class="btn btn-default" data-name="select-personnels" data-toggle="modal" data-target="#SelectableSearchEmployeeModal">#Resources.SelectPersonals</button>
<span data-name="selected-employees-numbers"></span>
</div>
</div>
<div class="form-group">
#Html.BootstrapCheckBoxFor(model => model.ShowReportSectionBySection)
#Html.BootstrapCheckBoxFor(model => model.ShowEachGroupInSeperatedPage)
</div>
<hr />
<div class="form-group">
#Html.BootstrapSubmitButton(false, new Dictionary<string, object> { { "name", "command" }, { "value", Resources.Observation } }, Resources.Observation)
#Html.BootstrapSubmitButton(false, new Dictionary<string, object> { { "name", "command" }, { "value", Resources.Print }, { "class", "btn btn-default" } }, string.Format("<span title=\"{0}\" class=\"glyphicon glyphicon-print\"></span>", Resources.Print))
#Html.BootstrapCancelButton()
</div>
</div>
}
</div>
<div class="#Model.ReportViewerVisibilityCssClass" style="direction: ltr;">
<hr />
#Html.Stimulsoft().StiMvcViewer(new StiMvcViewerOptions
{
Actions =
{
GetReportSnapshot = "KardexStimulsoftReport",
ViewerEvent = "KardexViewerEvent"
},
Toolbar =
{
//Visible = false,
ShowParametersButton = false
}
})
</div>
My Actions:
[AuthorizeUser(Permissions = "131213")]
public ActionResult KardexStimulsoftReport()
{
KardexReportModel model = TempData[ReportTempDataName] as KardexReportModel;
if (model == null)
{
StiReport emptyStiReport = new StiReport();
return StiMvcViewer.GetReportSnapshotResult(emptyStiReport);
}
ServicePredicateBuilder<DtoEmployee> servicePredicateBuilder = MdsGridViewHelper.CreateGridViewCriteria<DtoEmployee>(model.SelectedEmployeesFiltering, "", 0, 0, new List<string>());
servicePredicateBuilder.PaginationData = null;
MorMamReports morMamReports = new MorMamReports(SecurityContext.GetCurrentUserForReport);
#region بدست آوردن شروط
if (!string.IsNullOrWhiteSpace(model.SelectedEmployeesEmpNoInJsonFormat))
{
var selectedEmpNos = JsonConvert.DeserializeObject<List<int>>(model.SelectedEmployeesEmpNoInJsonFormat);
if (selectedEmpNos.Count > 0)
servicePredicateBuilder.Criteria = servicePredicateBuilder.Criteria.And(q => q.Emp_No, OperatorEnum.Contain, selectedEmpNos);
}
#endregion
StiReport stiReport = morMamReports.GetKardex(
servicePredicateBuilder,
model.StartPersianDateTime,
model.EndPersianDateTime,
Resources.Menu_131213,
string.Format("{0} {1} {2} {3}", Resources.FromDate, model.StartPersianDateTime.ToShortDateString(), Resources.ToDate, model.EndPersianDateTime.ToShortDateString()),
model.ShowEachGroupInSeperatedPage,
model.ShowReportSectionBySection ? GroupByItemEnum.Section : GroupByItemEnum.Employee);
return StiMvcViewer.GetReportSnapshotResult(stiReport);
}
[AuthorizeUser(Permissions = "131213")]
public ActionResult KardexViewerEvent()
{
return StiMvcViewer.ViewerEventResult();
}
This issue will be fixed in the next official release of Stimulsoft Reports. It will be 2016.1 release.
I meet this issue in the 2016.1 version.
In minified version of the stimulsoft.viewer.js the line of the code looks like this:
for(o in e)u.push(parseInt(e[o].replace("px","")));
The same approach of using for in, is found in designer's code. I'm forced to edit minified code to workaround the problem.