I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();
Related
I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146"enum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.
I have a master-detail page which has a clone button. On clicking the clone button, the data of the first list item is put into a model (detailModel - which is declared in component.js) and a new screen is opened. The data of that list item is binded to some input fields. When any of that input field is updated/erased and then user navigates back without saving it and comes again on that page, that updated/erased field stays blank. I want that data to come in that field which was coming earlier but it is coming blank. Data in my model is also not changing. Below is the code :
Component.js :
this.detailModel = new sap.ui.model.json.JSONModel();
this.detailModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneWay);
sap.ui.getCore().setModel(this.detailModel, "detailModel");
Controller.js :
/*eslint-disable no-console, no-alert */
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"hmel/TravelandGuestHouse/controller/formatter",
"sap/m/MessageToast",
"sap/m/MessageBox",
"sap/m/Button",
"sap/m/Dialog",
"sap/m/Text",
'sap/m/Label',
'sap/m/TextArea'
], function (Controller, JSONModel, formatter, MessageToast, MessageBox, Button, Dialog, Text, Label, TextArea) {
"use strict";
return Controller.extend("hmel.TravelandGuestHouse.controller.CloneTravelRequest", {
onInit: function () {
this.router = sap.ui.core.UIComponent.getRouterFor(this);
//for cloning request
this.detailModel = sap.ui.getCore().getModel("detailModel");
this.getView().setModel(this.detailModel, "detailModel");
//for sending data to guest house screen
this.getView().byId("date").setDateValue(new Date());
this.router.attachRoutePatternMatched(this._handleRouteMatched, this);
},
_handleRouteMatched: function (evt) {
if (evt.getParameter("name") !== "CloneTravelRequest") {
return;
}
this.getView().invalidate();
var that = this;
//fetching Train Names
$.ajax({
url: "/Non_sap_create_requests/odata/TravelPrpTrainDetails",
method: "GET",
dataType: "json",
success: function (data) {
that.getView().getModel("Model").setProperty("/TravelPrpTrainDetails", data.value);
var tempModel = that.getView().getModel("detailModel");
var train = tempModel.getData().TrainName;
var trainKey = formatter.pickTrainKeyFromModel(data.value, train);
that.getView().byId("trainName").setSelectedKey(trainKey);
that.setLocations();
var nameofPass = tempModel.getData().NameOfPsngr;
if (nameofPass === "" || nameofPass === null) {
that.getView().byId("nameOfP").setValue(tempModel.getData().Requestee);
}
},
error: function (err) {
console.log(err.message);
}
});
var fdate = new Date();
this.getView().byId("date").setDateValue(new Date());
this.getView().byId("date").setMinDate(fdate);
}
});
});
If you can change to an oDataModel you can use the resetChanges method.
If you cant, you `ll have to do it a little bit more manually. Once the new windows pops up save the data the user will change and if he cancels it restore the saved data on the jsonDataModel.
Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});
I have an issue with a dropdownlist and I can't figure it out how to solve it.
There are two different way to get into my view: Add New and Edit.
1) Add New: In this situation my dropdownlist is related to another one, and everything works great.
the dropdownlist is locked and empty until I select something in the other one.
2) Edit: In this situation my dropdownlist is already binded using stored data. Of course if I change the selected item in the "parent" one I want to change data to the children too.
The problem appears in the 2 case: When I select something else out of the stored data in the related dropdownlist.
It binds the correct data, but it gives an empty item as first, and not the first of the data.
How can I solve it?
<%=Html.Kendo().DropDownListFor(model => model.GNR_FK)
.Name("GNR_FK") .BindTo((IEnumerable<Models.Widget.Combo>)ViewData["Customer"])
.DataTextField("descriptionText")
.DataValueField("valueID")
.Value(Model.GNR_FK.ToString())
.Events(e =>
{
e.Select("onSelect");
})
%>
<%=Html.Kendo().DropDownListFor(model => model.CNT_FK) .BindTo((IEnumerable<Models.Widget.Combo>)ViewData["Sender"])
.Name("CNT_FK")
.DataTextField("descriptionText")
.DataValueField("valueID")
%>
Condition:
if (Model.PK == 0)
{
loadValues(current);
}
else
{
loadEditValues(current);
}
public JsonResult loadValues(Models.Model current, int PK = 0)
{
IDataReader sender = Model.getSender(PK);
Models.Widget.Combo SenderNA = new Models.Widget.Combo();
List<Models.Widget.Combo> receiveSender = new List<Models.Widget.Combo>();
SenderNA.valueID = 0;
SenderNA.descriptionText = "NA";
receiveSender.Add(SenderNA);
while (sender.Read())
{
Models.Widget.Combo newItem = new Models.Widget.Combo();
newItem.valueID = int.Parse(sender["PK"].ToString());
newItem.descriptionText = sender["SURNAME"].ToString();
receiveSender.Add(newListItem);
}
return Json(receiveSender, JsonRequestBehavior.AllowGet);
}
private void loadEditValues(Models.Model current)
{
int selected = current.GNR_FK;
IDataReader sender = current.getSender(selectedCustomer);
Models.Widget.Combo SenderNA = new Models.Widget.Combo();
List<Models.Widget.Combo> receiveSender = new List<Models.Widget.Combo>();
SenderNA.valueID = 0;
SenderNA.descriptionText = "NA";
receiveSender.Add(SenderNA);
while (sender.Read())
{
Models.Widget.Combo newItem = new Models.Widget.Combo();
newItem.valueID = int.Parse(sender["PK"].ToString());
newItem.descriptionText = sender["SURNAME"].ToString();
receiveSender.Add(newListItem);
ViewData["List"] = receiveSender;
}
}
Script:
function onSelect(e) {
var dataItem = this.dataItem(e.item);
var PK = dataItem.valueID;
$.ajax({
type: 'POST',
url: '/Project/loadValues',
data: "{'PK':'" + PK + "'}",
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#CNT_FK").data("kendoDropDownList").dataSource.data(result);
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
}
Regards
Problem Solved!
It was missing the select method to automatically select the first item after changing data!
success: function (result) {
var dropdown = $("#CNT_FK").data("kendoDropDownList");
dropdown.dataSource.data(result);
dropdown.select(0);
},
I'm testing MVC for a demo and I managed to scrap together some pieces but now I am having trouble with an Html.ActionLink. The intent is to present the user with a series of dropdownlists that they must select before the ActionLink is shown. To do that I've copied some JQuery to hide/show my dropdownlists (as selections are made) and the ActionLink. I added an alert to my JQuery to check my values and via the alert it all looks good. But if I debug the controller the parm values are defaulted to 0. I'm not sure what code to include but I will try to include the relevant parts. I think it's something basic.
Here are the dropdown lists and ActionLink.
#Html.DropDownListFor(m => m.selected_env_ID, new SelectList(Model.Environments, "env_ID", "env_DESC"), "*Select an environment")
#Html.DropDownListFor(m => m.selected_app_ID, new SelectList(Model.Applications, "app_ID", "app_DESC"), "*Select an application",new { #hidden = "hidden" })
#Html.DropDownListFor(m => m.selected_job_ID, Enumerable.Empty<SelectListItem>(), "*Select a job", new { #hidden = "hidden" })
#Html.ActionLink("Submit", "Submit", new { id = Model.selected_job_ID, envid = Model.selected_env_ID }, new {id = "lnkSubmit" })
Here is the convoluted JQuery to hide/show and fill the cascading dropdowns.
<script>
$(document).ready(function ()
{
//Dropdownlist Selectedchange event
$("#selected_app_ID").change(function () {
var id = $('#selected_app_ID').val(); // id value
if (id == 0) {
$('#selected_job_ID').hide();
} else {
$('#selected_job_ID').show();
$("#selected_job_ID").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("SelectJobs")',
dataType: 'json',
data: { id: $("#selected_app_ID").val() },
success: function (jobs) {
// jobs contains the JSON formatted list of jobs passed from the controller
$("#selected_job_ID").append('<option value=0>*Select a job</option>');
$.each(jobs, function (i, job) {
$("#selected_job_ID").append('<option value="'
+ job.job_ID + '">'
+ job.job_DESC + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve jobs.' + ex);
}
});
}
return false;
});
//ddl select change
$("#selected_env_ID").change(function () {
var name = $('#selected_env_ID option:selected').text(); //Item1
var id = $('#selected_env_ID').val(); // id value
if (id == 0) {
$('#divSubmit').hide();
$('#selected_app_ID').hide();
$('#selected_job_ID').hide();
} else {
$('#selected_app_ID').show();
}
});
//ddl select change
$("#selected_job_ID").change(function () {
var name = $('#selected_job_ID option:selected').text(); //Item1
var id = $('#selected_job_ID').val(); // id value
var envid = $('#selected_env_ID').val(); // id value
if (id == 0) {
$('#divSubmit').hide();
} else {
$('#divSubmit').show();
alert("envid=" + envid + " jobid=" + id);
}
});
}); // end document ready
</script>
My controller has this and id and envid end up being 0:
public ActionResult Submit(int id = 0,int envid = 0) {
If I need to include something else just let me know.
Here is the method that fills the job dropdown list. This works without issues. It's the Html.ActionLink call to Submit that fails to include the parameters.
public JsonResult SelectJobs(int id)
{
db.Configuration.ProxyCreationEnabled = false;
IEnumerable<t_job> jobs = db.t_job.Where(j => j.app_ID == id).ToList();
return Json(jobs);
}
Your link
#Html.ActionLink("Submit", "Submit", new { id = Model.selected_job_ID, envid = Model.selected_env_ID }, new {id = "lnkSubmit" })
is rendered on the server side before you make any selection in the dropdowns. If the initial values of selected_job_ID and selected_env_ID are zero or null, then those values will be passed to the controller (have a look at the rendered html).
If you want to pass the values selected in you drop downs, you could either modify the links href attribute in the drop down change events, or create a button instead of a link, and do a redirect in the buttons click event based on the dropdown values.
You need to use JSON.stringify():
data: JSON.stringify({ id: $("#selected_app_ID").val() }),