In my web application, I am using the AjaxBeginForm method to send data to the controller without submitting the form and refreshing the page.
Here is my current code when I click the confirm button it passes the data in PaymentType, PayAmount and Note but not passing the attachment as a byte.
Is there any way of doing this or an alternative way?
This is my current code.
In the View
< div class = "x_panel" >
#using (Ajax.BeginForm("UpdatePayments", "TaskMains", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "PartialViewPaymentHistory" },
new
{
id = "frmTPaymnets"
}))
{
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model = > model.TaskDetailsList.First().Service_Price, htmlAttributes: new { #class = "control-label col-md-3" })
< div class = "col-sm-8" >
#Html.EditorFor(model = > model.TaskDetailsList.First().Service_Price, new { htmlAttributes = new { #class = "form-control", #disabled = "disabled" } })
</div>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
#Html.HiddenFor(model = > model.TaskDetailsList.First().Id)
<div class="col-md-4 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model = > model.TaskPaymentsViewModel.Payment_Type, htmlAttributes: new { #class = "control-label col-md-3" })
< div class = "col-sm-8" >
#Html.DropDownList("Payment_Type", null, "Select Payment Type", new { #class = "form-control js-dropdown js-PaymentType", #Id = "PayType" })
#Html.ValidationMessageFor(model = > model.TaskPaymentsViewModel.Payment_Type, "", new { #class = "text-danger" })
< /div>
</div>
</div>
<div class="col-md-2 col-sm-3">
<div class="form-group row">
#Html.LabelFor(model => model.TaskPaymentsViewModel.Cash_Direction, htmlAttributes: new { #class = "control-label col-md-6" })
<div class="col-sm-4">
#Html.EditorFor(model => model.TaskPaymentsViewModel.Cash_Direction, new { htmlAttributes = new { #class = "form-control", #id = "txtCashDirection", #disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.TaskPaymentsViewModel.Cash_Direction, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-2 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model = > model.TaskPaymentsViewModel.Amount, htmlAttributes: new { #class = "control-label col-md-3" })
< div class = "col-sm-8" > #Html.EditorFor(model = > model.TaskPaymentsViewModel.Amount, new { htmlAttributes = new { #class = "form-control", placeholder = "Type Bill Amount", #id = "txtAmount" } })
#Html.ValidationMessageFor(model = > model.TaskPaymentsViewModel.Amount, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model => model.TaskPaymentsViewModel.Note, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.EditorFor(model => model.TaskPaymentsViewModel.Note, new { htmlAttributes = new { #class = "form-control", placeholder = "Type Additional Notes here" } })
#Html.ValidationMessageFor(model => model.TaskPaymentsViewModel.Note, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
Attachment
<div class="col-md-10">
<input type="file" name="ImageData" id="ImageData" multiple="multiple" data-id="Img" onchange="checkImage(this)" />
#Html.ValidationMessageFor(model => model.Attachment, "", new { #class = "text-danger" })
</div>
</div>
<img id="Img" src="" alt="" width="100" height="100" class="ml-1" />
</div>
<input type="button" onClick="UpdatePayments();"/>
</div>
Script for attachment section
<script type="text/javascript">
$('.js-dropdown').select2({
width: '100%', // need to override the changed default
});
function checkImage(obj) {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'pdf'];
var ResponceImgId = $(obj).data('id');
const fileSize = obj.files[0].size / 1024 / 1024; // in MiB
const fileSizeRule = 3.0;
if ($.inArray($(obj).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
Swal.fire({
icon: 'error',
title: 'Upload Error',
text: 'Only .jpeg, .jpg, .png, .gif, .bmp ,pdf formats are allowed.',
footer: 'Please attach again'
})
}
else if (fileSize > fileSizeRule) {
Swal.fire({
icon: 'error',
title: 'Maximum size exceeded',
text: 'File size should be less than 3 MB.',
footer: 'Please add a attachment less than 3 MB'
})
}
else {
var files = obj.files;
var reader = new FileReader();
name = obj.value;
reader.onload = function (e) {
$('#' + ResponceImgId).prop('src', e.target.result);
};
reader.readAsDataURL(files[0]);
}
}
</script>
This is the ajax call
function UpdatePayments() {
try {
var $form = $("#frmTPaymnets");
var xModel = $form.serialize();
$.ajax({
url: '../UpdatePayments',
type: 'POST',
dataType: 'html',
cache: false,
async: false,
data: xModel,
success: function (data) {
$("#PartialViewPaymentHistory").html(data);
toastr.success('#ViewBag.ToastSucess');
document.getElementById('txtAmount').value = "";
}
});
}
catch (err) {
console.log(err.message)
}
}
Related
In my view, I'm using select2Combobox as my dropdowns.
Here when the Country selection changes, I pass that selected id to the JSON result and get the results, assigning for the provinces Combobox.
When it happens, the dropdown view is changed to the square from the rounded edges.
I want to know how to add the same styles to the select2 combo boxes.
this is my code.
<div class="col-md-6 col-sm-6">
<div class="form-group row"> #Html.LabelFor(model => model.Country_Id, htmlAttributes: new { #class = "control-label col-md-3 required" }) <div class="col-sm-8">
<span class="asterisk_input"></span> #Html.DropDownList("Country_Id", null, "Select Country", new { #class = "form-control js-dropdown js-Country", #Id = "Country", #data_map = Model.TempId, #required = true }) #Html.ValidationMessageFor(model => model.Country_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row"> #Html.LabelFor(model => model.Province_Id, htmlAttributes: new { #class = "control-label col-md-3 required" }) <div class="col-sm-8">
<span class="asterisk_input"></span> #Html.DropDownListFor(model => model.Province_Id, new List <SelectListItem>(), new { #class = "form-control js-dropdown js-Province", #id = "ddlProvId" + Model.TempId, #data_map = Model.TempId, #required = true }) #Html.ValidationMessageFor(model => model.Province_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
Javascript
$(function () {
$('.js-Country').change(function () {
var mapperId = $(this).data('map');
setDropDownProvinces($(this).val(), mapperId)
});
});
function setDropDownProvinces(xVal, mapid) {
try {
$("#ddlProvId" + mapid).empty().trigger("changed");
$.ajax({
url: '/Account/FindProvinces',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: {
CountryId: xVal
},
success: function (data) {
if (data.Success == true) {
$("#ddlProvId" + mapid).select2({
width: '100%',
data: JSON.parse(data.items)
});
}
}
});
} catch (err) {
console.log(err.message)
}
}
This is the dropdown before selecting the country
This is after the selection.
In the success function of your ajax call try this line after mapping the result:
$("#ddlProvId" + mapid).addClass('form-control js-dropdown js-Province');
Source:
jQuery $.addClass()
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.
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!
My cascading drop down box work fine from within visual studio 2015 and iisexpress. But when hosting on IIS or selecting IIS as server in visual studio the controller action to populate the second drop drown box is not called!
I'm new to Javascript and and not very firm with asp.net mcv with I use here.
I use VS2015, ASP.NET Mvc
Create.cshtml:
#model Bethesda2017.Models.AuftragEditViewModel
#{
ViewBag.Title = "Neuer Reparaturauftrag";
}
<style>
body {
background: url(/Bilder/Bethesda4Web.jpg);
background-position: right top;
background-size: 12%;
background-repeat: no-repeat;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal body">
<h4>Neuer Reparaturauftrag</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
-- Some irrelavant controls extracted here ----
<div class="form-group">
#Html.LabelFor(model => model.STORT_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor( model => model.STORT_ID, Model.StandortListe, "Bitte wählen!", new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DropDownListFor(model => model.STORT_ID, Model.StandortListe, "Bitte wählen!", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.STORT_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TRAKT_ID, htmlAttributes: new { #class = "control-label col-md-2" })
#*#Html.DropDownListFor(model => model.TRAKT_ID, Model.TraktListe, "", new { #class = "form-control col-md-2" } )*#
<div class="col-md-10">
#Html.DropDownListFor(model => model.TRAKT_ID, Model.TraktListe, "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TRAKT_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ETAGE_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ETAGE_ID, Model.EtageListe, "", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.ETAGE_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RAUM_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.RAUM_ID, Model.RaumListe, "", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.RAUM_ID, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.DerAuftrag.FHD_KOMPLETT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DerAuftrag.FHD_KOMPLETT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DerAuftrag.FHD_KOMPLETT, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Speichern" class="btn btn-default" />
</div>
</div>
</div>
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
var trakt_idUrl = '#Url.Action("FetchTrakte", "Auftrag")';
var trakte = $('#TRAKT_ID');
var etage_idUrl = '#Url.Action("FetchEtagen", "Auftrag")';
var etagen = $('#ETAGE_ID');
var raume = $('#RAUM_ID');
var raum_idUrl = '#Url.Action("FetchRaume", "Auftrag")';
$('#STORT_ID').change(function () {
trakte.empty();
etagen.empty();
raume.empty();
$.getJSON(trakt_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
trakte.append($('<option></option>').val('').text('Bitte Trakt wählen!'));
$.each(data, function (index, item) {
trakte.append($('<option></option>').val(item.TRAKT_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
$('#TRAKT_ID').change(function () {
etagen.empty();
raume.empty();
$.getJSON(etage_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
etagen.append($('<option></option>').val('').text('Bitte Etage wählen!'));
$.each(data, function (index, item) {
etagen.append($('<option></option>').val(item.ETAGE_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
$('#ETAGE_ID').change(function () {
raume.empty();
$.getJSON(raum_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
raume.append($('<option></option>').val('').text('Bitte Raum wählen!'));
$.each(data, function (index, item) {
raume.append($('<option></option>').val(item.RAUM_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
</script>
When selecting an entry in the first drop down box the java script
$('#STORT_ID').change(function () ...
gets called and trakte, etagen and raume are set empty but the next step:
$.getJSON(trakt_idUrl, { STORT: $(this).val() }, function (data) {...
which should call the method
public JsonResult FetchTrakte(string STORT )
{
List<Trakt> _l = FetchTrakteList(STORT);
if ( _l.Count<1 )
{
Trakt _s0 = new Trakt() { TRAKT_ID = "00", BEZEICHNUNG = "keine Daten" };
_l.Add(_s0);
}
return Json(_l, JsonRequestBehavior.AllowGet);
}
is only called when using iisexpress but not with IIS!
Where is the problem or how to examine what is going on here?
I have the following script
$(function () {
$("#btnConfirmParticipants").click(function () {
var jsonArray = [];
$(".participantForm").each(function () {
jsonArray.push({ Name: ($(this).find("#Name").val()), Surname: ($(this).find("#Surname").val()), BirthDate: ($(this).find("#BirthDate").val()) });
});
var data = {
participants: JSON.stringify(jsonArray),
houseName: $('select[name="SelectedHousesParticipants"]').val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
$.ajax({
type: "POST",
url: "/ClientReservations/ChangeHouseParticipants",
data: data,
contentType: "application/json; charset=utf-8",
success: function (response) {
},
});
});
});
This script calls the method in controller
[HttpPost]
[Authorize(Roles ="Klient")]
public ActionResult ChangeHouseParticipants(List<Participant> participants,string houseName)
{
return View();
}
When during execution I receive
Invalid JSON primitives.
Any proposals how to solve it?
Additionaly using partial views to display each essential fields for every Participant
Partial View for all Participants
<div>
#foreach (Participant item in Model)
{
<div >
#Html.Partial("~/Views/Shared/_HouseParticipant.cshtml", item)
</div>
}
</div>
Partial view of single Participant
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal participantForm">
<h4>Uczestnik</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" } )
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { id = "Name", htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { id = "Surname", htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BirthDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BirthDate, new { id = "BirthDate", htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
}
Instead of
var data = {
participants: JSON.stringify(jsonArray),
houseName: $('select[name="SelectedHousesParticipants"]').val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
do
var data = {
participants: jsonArray,
houseName: $('select[name="SelectedHousesParticipants"]').val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
var jsonData = JSON.stringify(data);
and then pass jsonData in request.