I post the data in the first screenshot. And I'm warning you to wait on the button. In the second picture, I print on the screen that the registration has been completed successfully.
But I cannot transfer the data to the database.
For these screens, I am using js file in the back part.
I haven't been able to solve the problem. can you help me ?
<form class="form fv-plugins-bootstrap5 fv-plugins-framework" action="#" id="kt_modal_add_customer_form" data-kt-redirect="/Dashboard/Cari">
<!--begin::Modal header-->
<div class="modal-header" id="kt_modal_add_customer_header">
<!--begin::Modal title-->
<h2 class="fw-bolder">Yeni Cari</h2>
<!--end::Modal title-->
<!--begin::Close-->
<div id="kt_modal_add_customer_close" class="btn btn-icon btn-sm btn-active-icon-primary">
<!--begin::Svg Icon | path: icons/duotune/arrows/arr061.svg-->
<span class="svg-icon svg-icon-1">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
<rect opacity="0.5" x="6" y="17.3137" width="16" height="2" rx="1" transform="rotate(-45 6 17.3137)" fill="black"></rect>
<rect x="7.41422" y="6" width="16" height="2" rx="1" transform="rotate(45 7.41422 6)" fill="black"></rect>
</svg>
</span>
<!--end::Svg Icon-->
</div>
<!--end::Close-->
</div>
<!--end::Modal header-->
<!--begin::Modal body-->
<div class="modal-body py-10 px-lg-17">
<!--begin::Scroll-->
<div class="scroll-y me-n7 pe-7" id="kt_modal_add_customer_scroll" data-kt-scroll="true" data-kt-scroll-activate="{default: false, lg: true}" data-kt-scroll-max-height="auto" data-kt-scroll-dependencies="#kt_modal_add_customer_header" data-kt-scroll-wrappers="#kt_modal_add_customer_scroll" data-kt-scroll-offset="300px" style="max-height: 397px;">
<!--begin::Input group-->
<div class="fv-row mb-7 fv-plugins-icon-container">
<!--begin::Label-->
<label class="required fs-6 fw-bold mb-2">Cari Kodu</label>
<!--end::Label-->
<!--begin::Input-->
<input type="text" class="form-control form-control-solid" placeholder="" name="CariKodu" value="#ViewData["CariKodu"]">
<!--end::Input-->
<div class="fv-plugins-message-container invalid-feedback"></div>
</div>
<!--end::Input group-->
<!--begin::Input group-->
<div class="fv-row mb-7 fv-plugins-icon-container">
<!--begin::Label-->
<label class="required fs-6 fw-bold mb-2">Firma Ünvanı</label>
<!--end::Label-->
<!--begin::Input-->
<input type="text" class="form-control form-control-solid" placeholder="" name="FirmaUnvani">
<!--end::Input-->
<div class="fv-plugins-message-container invalid-feedback"></div>
</div>
<!--end::Input group-->
<!--begin::Input group-->
<div class="fv-row mb-7 fv-plugins-icon-container">
<!--begin::Label-->
<label class="required fs-6 fw-bold mb-2">Ticari Ünvan</label>
<!--end::Label-->
<!--begin::Input-->
<input type="text" class="form-control form-control-solid" placeholder="" name="TicariUnvani">
<!--end::Input-->
<div class="fv-plugins-message-container invalid-feedback"></div>
</div>
<!--end::Input group-->
<!--begin::Input group-->
<div class="fv-row mb-7 fv-plugins-icon-container">
<!--begin::Label-->
<label class="fs-6 fw-bold mb-2">
<span class="required">E-Posta</span>
<i class="fas fa-exclamation-circle ms-1 fs-7" data-bs-toggle="tooltip" title="" data-bs-original-title="Aktivasyon için E-Posta Adresi Zorunludur" aria-label="Aktivasyon için E-Posta Adresi Zorunludur"></i>
</label>
<!--end::Label-->
<!--begin::Input-->
<input type="email" class="form-control form-control-solid" placeholder="" name="EPosta">
<!--end::Input-->
<div class="fv-plugins-message-container invalid-feedback"></div>
</div>
<!--end::Input group-->
<!--begin::Input group-->
<div class="fv-row mb-7 fv-plugins-icon-container">
<!--begin::Label-->
<label class="required fs-6 fw-bold mb-2">Vergi Dairesi</label>
<!--end::Label-->
<!--begin::Input-->
<input type="text" class="form-control form-control-solid" placeholder="" name="VDairesi">
<!--end::Input-->
<div class="fv-plugins-message-container invalid-feedback"></div>
</div>
<!--end::Input group-->
<!--begin::Input group-->
<div class="fv-row mb-7 fv-plugins-icon-container">
<!--begin::Label-->
<label class="required fs-6 fw-bold mb-2">Vergi Numarası</label>
<!--end::Label-->
<!--begin::Input-->
<input type="text" class="form-control form-control-solid" placeholder="" name="VNo">
<!--end::Input-->
<div class="fv-plugins-message-container invalid-feedback"></div>
</div>
<!--end::Input group-->
</div>
<!--end::Scroll-->
</div>
<!--end::Modal body-->
<!--begin::Modal footer-->
<div class="modal-footer flex-center">
<!--begin::Button-->
<button type="reset" id="kt_modal_add_customer_cancel" class="btn btn-light me-3">İptal</button>
<!--end::Button-->
<!--begin::Button-->
<button type="submit" id="kt_modal_add_customer_submit" class="btn btn-primary">
<span class="indicator-label">Gönder</span>
<span class="indicator-progress">
Lütfen Bekleyiniz...
<span class="spinner-border spinner-border-sm align-middle ms-2"></span>
</span>
</button>
<!--end::Button-->
</div>
<!--end::Modal footer-->
<div></div>
</form>
<!--end::Form-->
"use strict";
var KTModalCustomersAdd = function () {
var t, e, o, n, r, i;
return {
init: function () {
i = new bootstrap.Modal(document.querySelector("#kt_modal_add_customer")), r = document.querySelector("#kt_modal_add_customer_form"), t = r.querySelector("#kt_modal_add_customer_submit"), e = r.querySelector("#kt_modal_add_customer_cancel"), o = r.querySelector("#kt_modal_add_customer_close"), n = FormValidation.formValidation(r, {
fields: {
CariKodu: {
validators: {
notEmpty: {
message: "Firmanın Cari Kodu Olmadan Kayıt Açamazsınız."
}
}
},
FirmaUnvani: {
validators: {
notEmpty: {
message: "Firma Ünvanı Olmadan Kayıt Açamazsınız."
}
}
},
"TicariUnvani": {
validators: {
notEmpty: {
message: "Firmanın Ticari Ünvanı Olmadan Kayıt Açamazsınız."
}
}
},
"EPosta": {
validators: {
notEmpty: {
message: "Aktivasyon İşlemi İçin E-Posta Adresini Girmelisiniz."
}
}
},
VDairesi: {
validators: {
notEmpty: {
message: "Firmanın Vergi Dairesi Olmadan Kayıt Açamazsınız."
}
}
},
VNo: {
validators: {
notEmpty: {
message: "Firmanın Vergi Numarası Olmadan Kayıt Açamazsınız."
}
}
},
city: {
validators: {
notEmpty: {
message: "City is required"
}
}
},
state: {
validators: {
notEmpty: {
message: "State is required"
}
}
},
postcode: {
validators: {
notEmpty: {
message: "Postcode is required"
}
}
}
},
plugins: {
trigger: new FormValidation.plugins.Trigger,
bootstrap: new FormValidation.plugins.Bootstrap5({
rowSelector: ".fv-row",
eleInvalidClass: "",
eleValidClass: ""
})
}
}), $(r.querySelector('[name="country"]')).on("change", (function () {
n.revalidateField("country")
})), t.addEventListener("click", (function (e) {
e.preventDefault(), n && n.validate().then((function (e) {
console.log("validated!"), "Valid" == e ? (t.setAttribute("data-kt-indicator", "on"), t.disabled = !0, setTimeout((function () {
t.removeAttribute("data-kt-indicator"), Swal.fire({
text: "Form bilgileri başarıyla gönderildi!",
icon: "success",
buttonsStyling: !1,
confirmButtonText: "Tamam, Anladım",
customClass: {
confirmButton: "btn btn-primary"
},
}).then((function (e) {
e.isConfirmed && (i.hide(), t.disabled = !1, window.location = r.getAttribute("data-kt-redirect"))
}))
}), 2e3)) : Swal.fire({
text: "Maalesef bazı hatalar tespit edildi, lütfen tekrar deneyin.",
icon: "error",
buttonsStyling: !1,
confirmButtonText: "Tamam, Anladım!",
customClass: {
confirmButton: "btn btn-primary"
}
})
}))
})), e.addEventListener("click", (function (t) {
t.preventDefault(), Swal.fire({
text: "İptal etmek istediğinizden emin misiniz?",
icon: "warning",
showCancelButton: !0,
buttonsStyling: !1,
confirmButtonText: "Evet, Kaydı İptal Et",
cancelButtonText: "Hayır, Devam Et",
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-active-light"
}
}).then((function (t) {
t.value ? (r.reset(), i.hide()) : "cancel" === t.dismiss && Swal.fire({
text: "Formunuz iptal edilmedi!.",
icon: "error",
buttonsStyling: !1,
confirmButtonText: "Tamam, Anladım!",
customClass: {
confirmButton: "btn btn-primary"
}
})
}))
})), o.addEventListener("click", (function (t) {
t.preventDefault(), Swal.fire({
text: "İptal etmek istediğinizden emin misiniz?",
icon: "warning",
showCancelButton: !0,
buttonsStyling: !1,
confirmButtonText: "Evet, İptal Et!",
cancelButtonText: "Hayır, Devam Et",
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-active-light"
}
}).then((function (t) {
t.value ? (r.reset(), i.hide()) : "cancel" === t.dismiss && Swal.fire({
text: "Formunuz iptal edilmedi!.",
icon: "error",
buttonsStyling: !1,
confirmButtonText: "Tamam, Anladım!",
customClass: {
confirmButton: "btn btn-primary"
}
})
}))
}))
}
}
}();
KTUtil.onDOMContentLoaded((function () {
KTModalCustomersAdd.init()
}));
Controller
[HttpPost]
public JsonResult Cari(Cariler p)
{
db.Cariler.Add(p);
db.SaveChanges();
return Json(p);
}
I tried using the post structure with ajax inside the js file. I was not successful.
I have completed the sweet alert record adding process as follows. It works successfully. Topic can be closed.
console.log(e);
debugger;
var EmpModel = {
CariKodu: $("#CariKodu").val(),
FirmaUnvani: $("#FirmaUnvani").val(),
TicariUnvani: $("#TicariUnvani").val(),
EPosta: $("#EPosta").val(),
VDairesi: $("#VDairesi").val(),
Telefon1: $("#Telefon1").val(),
VNo: $("#VNo").val()
};
$.ajax({
type: "POST",
url: "/Dashboard/Cari",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(EmpModel),
success: function (msg) { },
error: function (err) { alert(err.responseText) }
})
Related
I have an APS.Net web app Razor view where I attempt to display the Viewbag.errormessage.
The action method populates the viewbag but the view does not show the error message that is in the viewbag. It does not appear. Why?
The paragraph to which the Viewbag is attached to does not even appear per the 2nd pic. In the 1st pic, I can see that is there.
I also tried using 'TempData' but it produces the same result - not appearing.
Here is the action method (simplified):
[HttpPost]
public async Task<ActionResult> DeleteUserAccount(string userName, string
password)
{
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
ViewBag.errormessage = "The 'user name' or 'password' is
invalid - empty. Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
ViewBag.errormessage = "Your 'user name' is invalid. It
is not the same as the 'user name' used at original sign
in. Please try again.";
}
}
}
catch (Exception ex1)
{
}
return View();
}
Here is the view:
#Html.AntiForgeryToken()
<div class="login-panel">
#if (ViewBag.errormessage != null)
{
<p class="alert alert-danger" id="errorMessage">#ViewBag.errormessage</p>
}
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
$(".btn-yes4").click(function () {
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "User")',
data: { userName: holdUserName, password: holdPassword},
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
$("#myModal4").on('hidden.bs.modal', function () {
$("#myModal4").remove();
});
});
})
</script>
https://dotnetfiddle.net/U6HGHD
Ajax makes a call and does not re-render a page
Controller
[HttpPost]
//I made method snchronous as it has no await, and there are no resources to add await to
public ActionResult DeleteUserAccount(string userName, string password)
{
var errorMessage = String.Empty;
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
//since this method is ajax, the view will not re-render, so errors need
//to go into return value.
//ViewBag.errormessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
errorMessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
//ViewBag.errormessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
errorMessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
}
}
}
catch (Exception ex1){}
//return View();
//since this is ajax, I am returning a json
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
public ActionResult Index19()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index19</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
//put this in here
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
//fixed the following line
});
$(".btn-yes4").click(function () {
//put these here
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "Home")',
data: { userName: holdUserName, password: holdPassword },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
if (data.length > 0) {
$("#errorMessage").css("display", "block");
}
else {
$("#errorMessage").css("display", "none");
}
$("#errorMessage").text(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
//$("#myModal4").on('hidden.bs.modal', function () {
// $("#myModal4").remove();
//});
});
</script>
</head>
<body>
#Html.AntiForgeryToken()
<div class="login-panel">
#*took out condition, and started with style none*#
#*#if (ViewBag.errormessage != null)
{*#
<p class="alert alert-danger" id="errorMessage" style="display:none">#ViewBag.errormessage</p>
#*}*#
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I want to add some custom constraint to password validation. I want it to have at least a Lowercase and an uppercase and a digit.
<form id="userForm">
<input type="hidden" class="form-control" id="ID" />
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="FName">First Name</label>
<input type="text" class="form-control" id="FName" name="FName" />
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="LName">Last Name</label>
<input type="text" class="form-control" id="LName" name="LName" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="UserName">User Name </label>
<input type="text" class="form-control" id="UserName" name="UserName" />
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="Password">Password </label>
<input type="password" class="form-control" id="Password" name="Password" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$('#userForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function (validator, form, submitButton) {
},
fields: {
FName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
LName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
UserName: {
validators: {
notEmpty: {
message: 'Required!'
}
},
stringLength: {
min: 3,
max: 25,
message: 'Length should be between 3 to 25.'
},
},
Password: {
validators: {
notEmpty: {
message: 'Required!'
},
stringLength: {
min: 8,
max: 15,
message: 'Length should be between 8 to 15.'
}
}
},
}
});
</script>
I used callback at last:
$('#userForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function (validator, form, submitButton) {
},
excluded: [':disabled'],
fields: {
FName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
LName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
UserName: {
validators: {
notEmpty: {
message: 'Required!'
},
stringLength: {
min: 3,
max: 25,
message: 'Length should be between 3 to 25.'
}
}
},
Password: {
validators: {
notEmpty: {
message: 'Required!'
},
stringLength: {
min: 8,
max: 15,
message: 'Length should be between 8 to 5.'
},
callback: {
callback: function (value, validator, $field) {
var validv = true;
var messagev = '';
//Number
if (!value.match(/\d/)) {
validv = false;
messagev += 'Enter a number.<br />'
}
//Lowercase letter
if (!value.match(/[A-z]/)) {
validv = false;
messagev += 'Enter a lowercase charachter..<br />'
}
//Capital letter
if (!value.match(/[A-Z]/)) {
validv = false;
messagev += 'Enter a capital charachter.'
}
return {
valid: validv,
message: messagev
}
}
}
}
},
selectStatus: {
validators: {
notEmpty: {
message: 'Required!'
}
}
}
}
});
You can use below code for validation of password for Upper case, Lower case, and digit.
Where Value = field name you can add this code into Password Field.
// The password doesn't contain any uppercase character
if (value === value.toLowerCase()) {
return {
valid: false,
message: 'The password must contain at least one upper case character'
}
}
// The password doesn't contain any uppercase character
if (value === value.toUpperCase()) {
return {
valid: false,
message: 'The password must contain at least one lower case character'
}
}
// The password doesn't contain any digit
if (value.search(/[0-9]/) < 0) {
return {
valid: false,
message: 'The password must contain at least one digit'
}
}
I've been stuck almost two days now and still couldn't find a solution.
I have a WebGrid in a partial view, and I'm loading it inside the main view which has 4 search fields.
I'm using Request.IsAjaxRequest() to identify which view has to be loaded.
If it's an Ajax call I return the Partial View else the Main View. If I return the "Main View" the Dropdownlist value get reset as it refresh. I want to keep the Dropdownlist value selected by the user after the results has been loaded.
Here's my Main View,
<div class="row">
#if (Model != null)
{
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by State", new { #class = "form-font-size label-margin-top" })
#Html.DropDownList("stateList", (SelectList)ViewBag.StatesList, "ALL", new { #class = "form-control", #id = "ddlState" })
#*<select class="form-control" id="ddlState">
<option value="0">ALL</option>(SelectList)ViewBag.StatesList
<option value="1">NT</option>
<option value="2">WA</option>
<option value="3">QLD</option>
</select>*#
</div>
</div>
</div>
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by Job Id", new { #class = "form-font-size label-margin-top" })
<input type="text" value="#ViewBag.JobId" id="txtName" class="form-control uppercase" />
#*<div class="col-sm-7 col-md-6">
<input type="text" id="txtName" class="form-control uppercase form-control-search-panel-textbox-height" />
</div>*#
</div>
</div>
</div>
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by Client", new { #class = "form-font-size label-margin-top" })
<input type="text" value="#ViewBag.Client" id="txtClientName" class="form-control uppercase" />
#*<div class="col-sm-7 col-md-6">
<input type="text" id="txtClientName" class="form-control uppercase form-control-search-panel-textbox-height" />
</div>*#
</div>
</div>
</div>
<div class="col-md-4 col-lg-3">
<div class="well well-sm well-min-height well-panel-remove-top-padding">
<div class="form-group">
#Html.Label("Search by Location", new { #class = "form-font-size label-margin-top" })
<input type="text" value="#ViewBag.Location" id="txtLocation" class="form-control uppercase" />
#*<div class="col-sm-7 col-md-6">
<input type="text" id="txtClientName" class="form-control uppercase form-control-search-panel-textbox-height" />
</div>*#
</div>
</div>
</div>
<div class="col-xs-12 col-sm-8 increase-bottom-padding">
<span class="glyphicon glyphicon-search glyphicon-margin-right"></span>All Jobs
<span class="glyphicon glyphicon-search glyphicon-margin-right"></span>My Jobs
</div>
<div id="grid">
#Html.Partial("_JobInstructionWebGridPartial")
</div>
}
else
{
<div class="col-xs-12 col-sm-8 increase-bottom-padding-job remove-left-right-padding">
<span class="glyphicon glyphicon-search glyphicon-margin-right"></span>All Jobs
</div>
#:<div class="col-md-12 alert alert-danger"><strong>You don't have any jobs, If you want to search any Job please click on "'All Jobs'" ..</strong></div>
}
</div>
Here's my Partial View
#model IEnumerable<SurveyManagement.Models.Job.ViewModel_JobInstruction_WebGrid>
#{
if (Model != null)
{
var grid = new WebGrid(source: Model, canPage: true, canSort: false, rowsPerPage: 10, ajaxUpdateContainerId: "jobgridcontent");
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="table-responsive">
<div class="table" id="tbljobbook">
#grid.GetHtml(tableStyle: "table table-striped table-bordered table-hover",
headerStyle: "jobinstruction-webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns:
grid.Columns(
grid.Column("JobId", header: "Job Id", style: "jobinstruction-row-style col-md-1", format: #<text><label class="lblJobId">#item.JobId</label> </text>),
grid.Column("ClientName", header: "Client Name", style: "col-md-2 job-webgrid-column-max-width uppercase"),
grid.Column("JobLocation", header: "Job Location", style: "col-md-2 job-webgrid-column-max-width"),
grid.Column("JobDescription", header: "Job Description", style: "col-md-2 job-webgrid-column-max-width"),
grid.Column("JobStatus", header: "Job Status", style: "jobinstruction-row-style col-md-1 uppercase"),
grid.Column("Action", format: #<text>
<button type="button" class="edit-user btn btn-info btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="Edit Job"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-swr btn btn-tumblr btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="SWR List"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-swr-new btn btn-facebook btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="New SWR"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-view btn btn-primary btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="Field Entry List"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-create btn btn-warning btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="New Field Entry"><i class="fa fa-list"></i></button>
<button type="button" class="job-entry-admin btn btn-danger btn-social-icon btn-sm" data-placement="top" data-toggle="tooltip" title="Admin"><i class="fa fa-list"></i></button></text>, style: "col-md-4 jobinstruction-row-style", canSort: false)
))
</div>
</div>
</div>
}
Calling the Controller Action on Dropdownlist change event,
$(document).ready(function () {
$('#ddlState').change(function () {
$.ajax({
type: "GET",
url: '#Url.Action("SearchJobDetails")',
data: { jobId: $('#txtName').val(), client: $('#txtClientName').val(), location: $('#txtLocation').val(), state: $("#ddlState option:selected").text() },
success: function (data) {
$('#grid').html(data);
}
});
});
});
Here is my Controller Action,
public ActionResult SearchJobDetails(string jobId = null, string client = null, string location = null, string state = null)
{
try
{
ViewBag.IsRecordsSave = false;
ViewBag.sectionid = 1;
ViewBag.Location = location;
ViewBag.Client = client;
ViewBag.JobId = jobId;
List<States> StateList = Enum.GetValues(typeof(States)).Cast<States>().ToList();
ViewBag.StatesList = new SelectList(StateList);
ViewBag.SelectedState = state;
if (Request.IsAjaxRequest())
{
return PartialView("_JobInstructionWebGridPartial", GetJobDetails(jobId, client, 0, location, state));
}
else
{
return View("JobInstructionsDetails", GetJobDetails(jobId, client, 0, location, state));
}
}
}
As you can see in the above controller, ViewBag.StatesList is where I assign the States in my Enum. If I return the View (else part), the dropdownlist value get reset. I managed to keep the input text box values by putting value="#ViewBag.Location" so it set the values back from ViewBag. How do I do that for the Dropdownlist? Please help.
You need to use Html.DropdownlistFor Just modify the code as shown in the example below.where m.jobID is the selected value. To keep the value after postback its wise to use Model always.
#Html.DropDownListFor(m => m.jobID, new SelectList(Model.Clients, "ID", "ClientName"),new { #class = "form-control" })
What I want to achieve is once the data got saved into database, when it goes back to client, it will automatically update the observable array. But somehow I couldn't make it happen.
This is my Server side code:
[HttpGet]
public JsonResult GetTasks()
{
var tasks = context.ToDoTasks.ToList();
return Json(tasks.Select(c => new TaskViewModel(c)).ToList(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult AddTask(string text, string date)
{
var nTask = new ToDoTask()
{
Text = text,
Date = DateTime.ParseExact(date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture),
IsDone = false,
Order = 1,
};
context.ToDoTasks.Add(nTask);
context.SaveChanges();
return Json(new TaskViewModel(nTask), JsonRequestBehavior.AllowGet);
}
This is my cshtml file code:
<form>
<div class="controls controls-row" style="margin-top:40px;">
<input class="span7" type="text" placeholder="Task to do" style="margin-right:4px;" id="oText">
<div id="task-date" class="input-append date">
<input data-format="MM/dd/yyyy" type="text" placeholder="MM/dd/yyyy" name="taskDate" id="oDate" />
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar">
</i>
</span>
</div>
<button class="btn" type="submit" style="margin-top:-10px;" data-bind="click: save">+</button>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox"> Mark all as complete
</label>
</div>
<div id="task-section" style="margin-top:20px;">
<ul data-bind="foreach: Tasks">
<!-- ko if: IsDone -->
<li>
<span><input type="checkbox" style="margin:-5px 5px 0px 0px;" data-bind="checked: IsDone" /></span>
<del><span data-bind="text: Text"></span></del>
<del><span class="task-date" data-bind="text: Date"></span></del>
</li>
<!-- /ko -->
<!-- ko ifnot: IsDone -->
<li>
<span><input type="checkbox" style="margin:-5px 5px 0px 0px;" data-bind="checked: IsDone" /></span>
<span data-bind="text: Text"></span>
<span class="task-date" data-bind="text: Date"></span>
</li>
<!-- /ko -->
</ul>
</div>
<div class="clearfix" style="margin-top:30px;">
<span class="pull-left" style="font-weight:bold;"><span data-bind="text: oItemLeft"></span> item left</span>
<span class="pull-right badge" style="cursor:pointer;" data-bind="click: remove">Clear # completed item</span>
</div>
</form>
And finally my JS:
var ViewModel = function (data) {
var self = this;
self.Tasks = ko.mapping.fromJS(data, {}, self.Tasks);
self.oItemLeft = ko.computed(function () {
var i = 0;
data.forEach(function (entry) {
if (!entry.IsDone) i++;
});
return i;
});
self.save = function () {
$.ajax({
url: "Home/AddTask",
type: "POST",
data: { text: $('#oText').val(), date: $('#oDate').val() },
success: function (response) {
ko.mapping.fromJS(response, ViewModel);
}
});
};
self.remove = function () {
alert('delete');
}
}
$(function () {
$.getJSON("/Home/GetTasks/", null, function (data) {
ko.applyBindings(new ViewModel(data));
});
// for datepicker
$('#task-date').datetimepicker({
language: 'pt-BR',
pickTime: false
});
});
self.save = function () {
$.ajax({
url: "Home/AddTask",
type: "POST",
data: { text: $('#oText').val(), date: $('#oDate').val() },
success: function (response) {
var task = ko.mapping.fromJS(response);
self.Tasks.push(task);
}
});
};
Also for oItemLeft you should be referring to self.Tasks instead of data:
self.oItemLeft = ko.computed(function () {
var i = 0;
self.Tasks().forEach(function (entry) {
if (!entry.IsDone) i++;
});
return i;
});
I am building a SPA per the guidance provided in John Papa's Jumpstart.
When I create the model, it has
modelObservable().entityAspect.entityState.isAdded() = true;
I update the text, dropdown and
modelObservable().entityAspect.entityState.isAdded() = false;
in my Datacontext:
var createProject = function (position) {
return manager.createEntity(entityNames.project,
{
positionId : position.id(),
start : position.start(),
memberId : position.memberId()
});
};
which is called from my add viewModel:
define(['services/datacontext', 'durandal/plugins/router', 'durandal/system', 'durandal/app', 'services/logger', 'services/uiService'],
function (datacontext, router, system, app, logger, ui) {
var model = ko.observable();
var position = ko.observable();
var hourTypes = ko.observableArray([]);
var isSaving = ko.observable(false);
// init
var activate = function (routeData) {
logger.log('Add View Activated', null, 'add', true);
var positionId = parseInt(routeData.id);
initLookups();
return datacontext.getPositionById(positionId, position).then(**createProject**);
};
var initLookups = function () {
logger.log('initLookups', null, 'add', true);
hourTypes(datacontext.lookups.hourTypes);
};
// state
**var createProject = function () {
return model(datacontext.createProject(position()));
}**
var addNewProject = function () {
if (position == undefined || position().id() < 1) {
console.log('callback addNewProject');
setTimeout(function () {
addNewProject();
}, 1000);
} else {
datacontext.addProject(position(), model);
console.log(model().id());
return;
}
}
var **save** = function () {
isSaving(true);
**datacontext.saveChanges()**
.then(goToEditView).fin(complete);
function complete() {
isSaving(false);
}
function goToEditView() {
isSaving(false);
var url = '#/Projects/';
router.navigateTo(url + model().id());
}
};
var vm = {
activate: activate,
hourTypes: hourTypes,
isAdded: isAdded,
model: model,
save: save,
title: 'Details View'
};
return vm;
});
the html
<section data-bind="with:model">
<h1 data-bind="text: name"> <i class="icon-asterisk" data-bind="visible: hasChanges" style="font-size: 30px;"></i></h1>
<div class="errorPanel"></div>
<div id="overview" class="project" >
<div class="row">
<div class="span4">
<label class="requiredLabel">Name*</label>
<input type="text" name="name" data-bind="value: name" style="width: 27em;" class="required" placeholder="Project Name" required validationMessage="Project Name required" /><span class="k-invalid-msg" data-for="title"></span>
</div>
</div>
<div class="row">
<div class="span3"><label class="requiredLabel">Start*</label></div>
<div class="span3"><label class="requiredLabel">End</label></div>
</div>
<div class="row">
<div class="span3"><input name="start" data-bind="shortDate: start" class="date required" required="required" placeholder="mm/dd/yyyy" style=" width:142px"></div>
<div class="span3"><input name="end" data-bind="shortDate: end" class="date" placeholder="mm/dd/yyyy" style=" width:142px"><span class="k-invalid-msg" data-for="end"></span></div>
</div>
<br/>
<div class="row">
<div class="span3"><label for="hourType" class="requiredLabel">Measure As*</label></div>
<div class="span2"><label for="hoursPerWeek" class="requiredLabel">Hours/Week</label></div>
<div class="span2"><label for="totalHours" class="requiredLabel">Total Hours</label></div>
</div>
<div class="row">
<div class="span3">
<select id="hourType" data-bind="options: $parent.hourTypes, optionsText: 'name', value: hourType" required validationMessage="Measure As required"></select><span class="k-invalid-msg" data-for="hourType"></span>
</div>
<div class="span2">
<input name="hoursPerWeek" type="number" min="1" max="120" required="required" data-bind="value: hoursPerWeek, validationOptions: { errorElementClass: 'input-validation-error' }, enable: hourType().id() == 1" class="hours required"" style="width: 80px;" validationMessage="Hours required"><span class="k-invalid-msg" data-for="projectHours"></span>
<span class="k-invalid-msg" data-for="totalHours"></span>
</div>
<div class="span2">
<input name="totalHours" type="number" min="40" max="2080" required="required" data-bind="value: totalHours, validationOptions: { errorElementClass: 'input-validation-error' }, enable: hourType().id() == 2" class="hours required"" style="width: 80px;" validationMessage="Hours required"><span class="k-invalid-msg" data-for="projectHours"></span>
<span class="k-invalid-msg" data-for="totalHours"></span>
</div>
</div>
<div class="row">
<div class="span4">
<label class="requiredLabel">Description*</label><span class="k-invalid-msg" data-for="description"></span><span id="posMinDesc" style="visibility:hidden"></span>
<textarea id="description" name="description" style="height: 200px; width: 650px;" data-bind="value: description, enabled:true, click: $parent.clearDefaults" rows="4" cols="60" class="richTextEditor k-textbox" required validationMessage="Description required" ></textarea>
</div>
</div>
</div>
<div class="button-bar">
<button class="btn btn-info" data-bind="click: $parent.goBack"><i class="icon-hand-left"></i> Back</button>
<button class="btn btn-info" data-bind="click: $parent.save, enable: $parent.canSave"><i class="icon-save"></i> Save</button>
</div>
</section>
The json breeze sends to my controller is this:
{
"entities": [
{
"Id": -1,
"Description": "poi",
"End": null,
"Gauge": 0,
"Score": 0,
"HourTypeId": 1,
"HoursPerWeek": 45,
"HourlyRate": null,
"TotalHours": null,
"WeightedHours": 0,
"CreditMinutes": 0,
"TotalCompensation": null,
"IsCurrent": false,
"Name": "poi",
"PositionId": 1,
"MemberId": 1,
"Start": "2011-09-01T00:00:00Z",
"undefined": false,
"entityAspect": {
"entityTypeName": "Project:#SkillTraxx.Model",
"defaultResourceName": "Projects",
"entityState": "Modified",
"originalValuesMap": {
"Name": "",
"HourTypeId": 0,
"HoursPerWeek": null,
"Description": ""
},
"autoGeneratedKey": {
"propertyName": "Id",
"autoGeneratedKeyType": "Identity"
}
}
}
],
"saveOptions": {}
}
As you can see, the above is incorrect b/c state is "Modified" and the Id = -1. This throws an error server side. I suppose I could trap the DbUpdateConcurrencyException, unwind the JObject and change "Modified" to added, but that's got code smell all over it.
If anyone can help me find the face-palm moment in all of this, I'm ready.
Thanks for looking!
FACE PALMED IT
I took Jays advice and started stripping away the html then I realize it was my handler.
The update method on shortDate handler was responsible. I wrapped it in an if statement not to send the update if the current state is added.
ko.bindingHandlers.shortDate = {
init: function (element, valueAccessor) {
//attach an event handler to our dom element to handle user input
element.onchange = function () {
var value = valueAccessor();//get our observable
//set our observable to the parsed date from the input
value(moment(element.value).toDate());
};
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
if (valueUnwrapped) {
element.value = moment(valueUnwrapped).format('L');
if (!viewModel.entityAspect.entityState.isAdded())
{
**viewModel.entityAspect.setModified();**
}
}
}
};