Add Selected value from Combo Box to session and retrieve - javascript

In my asp.net web application, I load some data to the combo box in the Nav bar.
I want to do when someone selects the value from the combo box need to set this value to the session.
Then again when reloads the page needs to check that session value and if it is not null, set the combo box value to the session value.
So far my code, when the combo box change event it adds the value to the session.
But again loading the page the method that checks whether the session value is null or not returns an error.
I checked the inspect element, their session value is set from the script. But checking that value returns error
On the Layout page, I wrote like
#{
List<SelectListItem> MyBranch = Session["MyBranch"] as List<SelectListItem>;
if (Session["SelectedBranch"].ToString() != null) // Error is : System.NullReferenceException: 'Object reference not set to an instance of an object.'
{
string currentbranch = Session["SelectedBranch"].ToString();
MyBranch.Where(x => x.Value == currentbranch).First().Selected = true;
}
}
This is the combo box
<div class="dropdown">
#Html.DropDownList("MyBranch", MyBranch, new { #class = "form-control js-dropdown js-MyBranch", #Id = "Branch" })
</div>
This is getting the combo box change value and setting it to the session
$(function () {
$('.js-MyBranch').change(function () {
var bId = document.getElementById('Branch').value;
sessionStorage.setItem("SelectedBranch", d);
});
});

Related

Value Given when tick box is checked :Undefined Array Key

When check box is selected, it copies value from customer to invoice party. So I am assuming that when check box selected. value is automatic. but it is saying undefined array key.
function EnableDisableTextBox(tickSame) {
var shipper = document.getElementById("iP");
var customer = document.getElementById("consignee").value;
document.getElementById("iP").value=customer;
shipper.disabled = tickSame.checked ? true : false;
if (shipper.enabled) {
shipper.blur();
}
}
I hope you are submitting the form to the server side. Disabled inputs will not submit data when submitting the form. Instead you can use readonly attribute to make to non editable (Even you can make it look like disabled with css)
function EnableDisableTextBox(tickSame) {
var shipper = document.getElementById("iP");
var customer = document.getElementById("consignee").value;
document.getElementById("iP").value=customer;
shipper.readonly= tickSame.checked ? true : false;
if (shipper.readonly) {
shipper.blur();
}
}

Dynamically check javascript value after database update

I am developing a dynamically generated and self updating form in ASP.NET MVC using javavascript, Jquery, JSON/Ajax calls.
Here is how I set up my view code from the controller. I loop through all available controls from the controller:
<ul>
#using (Html.BeginForm("Index", "WebMan", FormMethod.Post)) {
foreach (var row in Model.controls)
{
<li>
<label>#row.Name</label>
#if (row.ControlType == "STRING" || row.ControlType == COMMENT")
{
<input type="text" name="#row.Name" id="#row.NameID" value="#row.Value" data-original-value="#row.Value" class="form-control data-field" style="width: 300px"/>
}
else if (row.ControlType == "DDL")
{
<select name="#row.Name" id="#row.NameID" class="form-control data-field" value="#row.Value" data-original-value="#row.Value" style="width: 300px">
#foreach (var o in row.Options)
{
<option value="#o.Value">#o.Text</option>
}
</select>
}
</li>
}
<button type="submit">Update</button>
}
</ul>
(notice that I set the value to the value from the database and I also set the “data-original-value” to the value from the database as well)
I am using the “data-original-value” to check to see if the value has changed later.
I also set up a javascript timer that executes every 5 seconds. This timer is meant to “update” the page. (code for timer below)
var interval = setInterval(function () { Update(); }, 10000);
When the timer executes, we loop through each control in the “data-field” class. This allows me to check each dynamically generated control.
Basically, If a user has edited a control, I DO NOT want to update that control, I want to ignore it. I only want to update that specific control if a user has not changed the value. When a user changes the value, the current value != orig value (Data-original-value), so we set the field to yellow and ignore the database update code.
function Update() {
UpdateControls();
}
function UpdateControls() {
$(".data-field").each(function () {
var nameAttr = $(this).attr('name');
var id = $(this).attr('id');
var val = document.getElementById(id).value;
var origVal = $(this).data("original-value");
if (origVal == val) {
//user did not change control, update from database
var url = "/WebMan/UpdateControlsFromDB/";
$.ajax({
url: url,
data: { name: nameAttr },
cache: false,
type: "POST",
success: function (data) {
if (data != null) {
document.getElementById(id).setAttribute("data-original-value", data);
document.getElementById(id).value = data;
}
else {
alert(data);
}
},
error: function (response) {
alert("Issue updating the page controls from database");
}
});
}
else {
document.getElementById(id).style.backgroundColor = "yellow";
//user changed control, do not update control and change color
}
});
}
If no change, this ajax method in my controller is called:
[HttpPost]
public ActionResult UpdateControlsFromDB(string name)
{
var curValue= db.Setup.Where(x => x.Name == name).Select(x =>Value).FirstOrDefault();
return Json(curValue);
}
The code works correctly if a user modifies the field. It senses that the user modifies the code, and changes the field yellow.
The part that does not work correctly, is if the database updates the field. When the database first updates the field, it looks great. We set the “data-original-field” value to the value as well, to tell our code that is should not turn yellow and the user has not modified it.
But after another update, “value” and “original-value” do not match. The code document.getElementById(id).value somehow gets the OLD version of the control. It does not get the current value. So then on next loop, the values don’t match and we stop updating from DB and the control turns yellow.
My issue is that my code senses that the control value changed (database update) and turns it yellow, when I only want to turn the control yellow when a USER has changed the value in the control.
I only want to change the control and prevent updating from DB when the control has been modified by the user.
Thank you for any help.

Check checkbox and set value on load content/page

I have a some shop. In cart (when usually user is not logged) is checkbox for set Invoice. If is not checked - then user get a bill.
On next step, user has to login, and goes to Procced page. When user goes ahead (after login page), can't change checkbox without back to cart.
I need to check (after login, on procced page) Customer is Company or normal user (private) and if user is Company, set the invoice as default.
I have that code:
(I know is not pure php - is some kind of framework)
<!-- CART PAGE with checkbox -->
<div id="additionalRealizationInfo">
?{foreach system.cart.optionsData option}
<label>
<input class="additionalRealizationInfoCheckbox"
type="checkbox"
?{if true == option.option.enabled}
checked="checked"
?{endif}
name="additional?{=system.randomNumber}"
value="${system.controllerUrl}ToggleOption/?{=option.name}" />
?{=option.title}
</label>
?{endforeach}
// The Value of checkbox is: toggleOption/facture
<!-- PROCCED PAGE without checkbox - On this page, after login, user see own choice from cart before login -->
<div id="additionalRealizationInfo">
<h2>Infos</h2>
<div>
?{foreach system.cart.optionsData option}
<div>
?{if true == option.option.enabled}
You get Invoice
?{else}
You get recive
?{endif}
</div>
?{endforeach}
</div>
</div>
<script type="text/javascript">
var isCompany = "?{=system.userLogged.InvoiceData.company}"; <!-- Company Name -->
var enableInvoice = "?{=system.cart.invoiceEnabled}";
if (isCompany.lenght > 0) {
$.get("${system.controllerUrl}setInvoiceEnabled",function(resp) {
$.get("${system.baseUrl}view/enableinvoice",function(resp) {
$("#additionalRealizationInfo").html(resp);
});
});
$.get("${system.controllerUrl}toggleOption/facture",function(resp) {
});
};
</script>
// string to check choice: ?{if system.cart.invoiceEnabled}
// system.baseURL/view/enableinvoice is some code to show, that invoice is set default (when script works)
What's wrong. It doesn't work
At first glance, I'd examine this line of code:
if (isCompany.lenght > 0) {
You've misspelled length. Try this:
if (isCompany.length > 0) {
OR, depending on if the value of the "isCompany" variable is true/false, you could write it as
if (isCompany) { // check boolean value instead
Hope that helps!
I change the script and it works, but only after I reload/refresh a page.
<!-- CART PAGE before and after login -->
var companyCustomer = "?{=system.userLogged.InvoiceData.company}";
//If user is logged, companyCustomer has a value. If not = ""
var enableInvoice = "?{=system.cart.invoiceEnabled}";
// If true = "1" , If false = "". That's not a boolean string.
var klik = $("#additionalRealizationInfo>label:first-child>input:checkbox");
if (companyCustomer) {
klik.prop('checked', true);
klik.prop("disabled", true);
klik.css('cursor','default');
$.get("${system.controllerUrl}toggleOption/facture",function(resp){
console.log(resp);
});
}; // End if (companyCustomer)
<!-- PROCEED PAGE after login -->
var companyCustomer = "?{=system.userLogged.InvoiceData.company}";
//If user is logged, companyCustomer has a value. If not = ""
var enableInvoice = "?{=system.cart.invoiceEnabled}";
// If true = "1" , If false = "". That's not a boolean string.
if (companyCustomer) {
if (enableInvoice) {
} else {
$.get("${system.controllerUrl}toggleOption/facture",function(resp){
console.log(resp);
});
}; // end if (enableInvoice)
}; // end if (companyCustomer)
How it execute on load, and dynamically change/set this toggle option?
When I didn't check the checkbox in CART PAGE, go next to login, and automatically go to PROCEED PAGE I get
enableInvoice = "";
I tried .ready and .load() and .live() and nothing works. Tried execute by .click but I don't want this method. I don't want to also refresh page after content shows up.

Modify the text inside an Html.EditorFor MVC with jquery?

I'm working on a web application in which I have an EditorFor field for a date as follows:
#Html.EditorFor(model => model.FECHA_RETIRO, new { htmlAttributes = new { #class = "form-control datepicker" } })
I have a jquery method that selects an element from a dropdown list and depending on the selection has to retrieve its date from the database. The method is:
$("#SIGLA_CURSO").change(function () {
var selectedValue = $("#SIGLA_CURSO").val();
$.post('#Url.Action("obtenerFechasCurso", "PRESTAMOes")', { idCurso: selectedValue }, function (listaDatos) {
alert(listaDatos);
// handle the server response here
$("#FECHA_RETIRO").val(listaDatos[0]);
$("#Fecha_Fin_Prestamo").val(listaDatos[1]);
});
});
The thing is I want the FECHA_RETIRO field to show the date that I retrieve from the database, however I can't get to modify it. If I try to show a date in a textbox it works, but it doesn't using the editorfor and I think that that is the field I need to modify.
Is it possible using jquery? Thank you.

Can't access ExtJS radio button on form

So I have an .aspx page. In this grid I'm adding a bunch of controls. The first control however is an ExtObject, not one of our preset VB.NET controls. When I go to access the value on the backend for this field with this code:
form.AndOr.getValue()
It doesn't work. I really have no idea what is wrong. Basically, the radio button value isn't saving when I save the rest of the stuff. So I tried to add code to do it. It was just defaulted to 'And' each time. Below is a snippet of code from the actual asp.net grid. Any ideas?
With .Item(2)
.Ref = "../Payee2"
.LabelWidth = 90
With .AddFieldSet("Payee 2")
.AddControl(New Forms.Control("", "../PayeeId")).Hidden = True
.AddControl(New Forms.Control("", "../AddressId")).Hidden = True
.AddExtObject("{xtype:'radiogroup', ref:'../AndOr', defaults:{name:'rdo-payee2'}, width:120, items:[{boxLabel:'And', checked:true, inputValue:'and'},{boxLabel:'Or', inputValue:'or'}]}")
Dim ddlPayee2 As New Controls.ComboBox("", "../PayeePreInfo2", "Payee")
With ddlPayee2
.ForceSelection = True
.TypeAhead = False
.EmptyText = "Select Payee Details"
.ValueField = "AddressId"
.XTemplate = "applicantTemplate"
.ClientStore = "applicantAddressStore"
.AddListener(Akcelerant.Framework.WebControls.Controls.EventType.Select, "function(){prefillPayee('PAYEE2');}")
End With
.AddControl(ddlPayee2)
With .AddControl(New Forms.Control("", "../FirstName", "First Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10483, True)
End With
With .AddControl(New Forms.Control("", "../LastName", "Last Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10484, True)
End With
The error it throws is this:
Stack overflow at line: 16736
edit:
reverted some changes back and everything saves EXCEPT that value into the DB.
go to add this line to the javascript save function
if (form.AndOr.getValue() == 'and') {
payeeRec.set('IsPayee2RequiredToSign', 1);
} else {
payeeRec.set('IsPayee2RequiredToSign', 0);
}
and i get this error:
form.AndOr is not defined
Does the Ext ref: mean something different than my controls and how I access them?
Added a ref to the item of checkWin.
Then the ref to the radio value became
checkWin.Payee2.AndOr.getValue()
With that it can recognize the control on the form.

Categories

Resources