I am developing my application in my MVC. I am using cascading dropdown list in my application. On selecting one i have 2 dropdown one is location and another one is employee. While selecting a location particular employee should be fetched in employee dropdown. I am using json result to retrieve the employee.
My code is
View Page
#Html.DropDownList("location", ViewBag.Location as SelectList, "Select the Location", new { id = "location" })
<div id=" employeediv" style="width:600px; height:50px">
<div style="float:left">
<label> Employee:</label>
</div>
<div style="margin-left:220px">
<select id="Employee" name="employee" style="width:150px"></select>
</div>
</div>
Script:
#section scripts{
<script type="text/javascript">
$('#location').change(function () {
#*var url = '#Url.Action("Employe", "Appt")';*#
//var url = "/Appt/Employee/"
debugger;
$.getJSON('/Appt/Employee/' + $('#location').val(), function (data) {
var item = '<option> Any </option>';
$.each(data, function (i, employee) {
item += "<option value ='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#employee").html(items);
});
});
</script>
}
Controller Code
public ActionResult CalendarView(int? id, int? CustomerUserid)
{
tblBusinessCategory bc = new tblBusinessCategory();
ViewBag.Location = new SelectList(from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc.LocationName);
return View();
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
My problem is While changing the location url is not redirecting to the controller and it is came out from its scope
$.getJSON('/Appt/Employee/' + $('#location').val(), function
Can anyone help me to solve this?
Thanks.
Related
I'm trying to create a WebGrid that allows me to update the data source with Ajax. The data source is assigned a List<> containing a model I created to hold the data. The WebGrid populates correctly and I have no problem sorting using the header of the WebGrid or paging.
The code for the View:
#model IEnumerable<TestDataModel.Models.TestData>
#{
ViewBag.Title = "Test Website";
var grid = new WebGrid(canPage: true, canSort: true, ajaxUpdateContainerId: "grid", ajaxUpdateCallback: "callBack");
grid.Bind(Model, rowCount: 10);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid" },
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
alternatingRowStyle: "webgrid-alternating-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: grid.Columns("This is a place holder,
I have a lot of columns"
));
}
<div>
<br />
<p>
Page Number: <input type="text" name="pageNumber" id="pageNumber" />
</p>
<p>
<input type="button" name="pageNumberButton" id="pageNumberButton" value="Page" />
</p>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#pageNumberButton").click(function () {
var pageNumber = $("#pageNumber").val();
$.ajax({
url: '#Url.Action("GetData", "Test")?pageNumber=' + pageNumber,
success: function (data) {
$("#grid").html(data);
},
error: function (data) {
alert("Error");
}
})
});
});
</script>
The bottom script tag is the ajax call that I'm trying to use to update the WebGrid. All that the "GetData" does is create a list pulling data from an SQL server and returns Json(testData, JsonRequestBehavior.AllowGet).
Code for Controller:
public ActionResult GetData(string pageNumber)
{
List<TestData> testData = new List<TestData>();
if (string.IsNullOrEmpty(pageNumber))
{
testData = Data.Data.TestDataGet();
}
else
{
try
{
var pageInt = Convert.ToInt32(pageNumber);
List<ParameterSQL> parameter = new List<ParameterSQL>();
parameter.Add(new ParameterSQL { Name = "#pageOffset", Value = pageInt });
testData = Data.Data.TestDataGet(parameter);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
return Json(testData, JsonRequestBehavior.AllowGet);
}
The error that I'm experiencing is when I push the button the WebGrid disappears entirely. The reason that I need to be able to update the WebGrid data source is because my table is millions of lines long and I'm only grabbing them a few thousand at a time. Once the user reaches the end of the of the list I want them to be able to load more using a SQL query that I already have working. Any help would be great, thanks.
I've a page '/order/new' that include 2 dropdown menues for customer & its address & a button that redirect to choose product to add to the order and I get the products in an array and pass the array to the '/order/new'..but when i redirect I don't get the selected customer & its address..I save the products which will be added in order in global array called hh which its get the data from ajax
I want to get the customer & its address after adding the product array
global.hh = new Array();
module.exports = {
getProduct: (req , res ) => {
var products = req.query.selectedProduct;
var total = req.query.sumTotal;
var btekh = hh.push(products)
}
getOrderProduct: (req , res) => {
let query1 = "SELECT * FROM `product`";
getConnection().query(query1 ,(err , result) => {
if(err) {
return res.status(500).send(err);
}
res.render('productOrder.ejs' , {
products: result
});
});
},
addOrderProduct: (req, res) => {
res.redirect('/order/new')
}
postOrder: (req ,res) => {
var products = req.session.products;
getConnection().query('INSERT INTO `order` ( clientId , addressId,orderStatusId) VALUES (?,?,?)', [req.body.selectUser, req.body.selectAddress,req.body.selectedStatus], (err,result) => {
if (err) {
console.log(err);
}
hh.slice(-1)[0].forEach(function (item) {
let insertedOrder = result.insertId;
let query = "INSERT INTO `orderProduct`( `orderIdProduct`, `productId`, `orderProductName`,`orderProductPrice`, `orderProductQuantity`, `orderProductTotal`) VALUES (?,?,?,?,?,?)";
getConnection().query( query , [insertedOrder,item.check,item.name,item.p,item.q,item.total] , (err , result)=>{
if (err) {
console.log(err);
}
res.end();
})
})
})
}
res.redirect('/')
}
app.get('/order/new' , addOrderPage)
app.use('/postOrder' , postOrder);
app.use('/order/product' , getProduct);
my ajax code:
////////////////add users's address///////////////////////////
$('#user').change(function(){
var item = $('#user').val();
$.ajax({
type:'GET',
data: { selectedId: item },
url:'/users/address',
success: function(data){
$('#address').empty();
$('address').append("<option disabled selected> Select Address..</option>");
$.each(data, function (index, addressObj) {
$('#address').append("<option value = '" + addressObj.addressId + "' > " + addressObj.addressName + " </option > ");
});
}
});
})
;
//////////////get the product to order/////////////
$('#save').click(function () {
var orderProduct = new Array();
$("#table input[type=checkbox]:checked").each(function () {
var row = $(this).closest("tr");
var message0 = row.find('#check').val();
var message1 = row.find('.name').text().trim();
var message3 = row.find('.currency').text().trim();
var message4 = row.find(".foo").val();
const result = {check: message0,name: message1,p: message3,q: message4 ,total: message3 * message4}
var hh = orderProduct.push(result);
});
console.log(orderProduct);
var totalPrice = 0;
orderProduct.forEach(function (item , index) {
totalPrice = totalPrice + item.total
})
$.ajax({
type: 'GET',
data: {selectedProduct: orderProduct , sumTotal: totalPrice},
url: '/order/product',
success: function (data) {
console.log(data);
}
})
})
My ejs for'/new/order':
<header>
<h2>New Order : </h2>
</header>
<form action="/postOrder" method="post" id="newForm" >
<label> User Name:</label>
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
</select>
<br>
<label>Product</label>
add product
<br>
<label>Status</label>
<select name="selectedStatus">
<% status.forEach((status) => { %>
<option value="<%= status.statusId %>"> <%= status.statusText %></option>
<% }) %>
</select>
<br>
<input type="submit" value="Save">
</form>
in these lines,
res.render('productOrder.ejs' , {
products: result
});
are you successfully getting all products from your DB back?
because in your AJAX call,
$.ajax({
type: 'GET',
data: {selectedProduct: orderProduct , sumTotal: totalPrice},
url: '/order/product',
success: function (data) {
console.log(data);
}
})
you're sending data, but not using it in your 'query1' here,
let query1 = "SELECT * FROM `product`";
I'm trying to get the flow of your program.
So the user goes to your webpage, they select a product, your webpage pings your REST server with the product information, your REST server pings your database looking for that product, then that data is rendered to this template here?
res.render('productOrder.ejs' , {
products: result
});
EDIT: You have to handle the user interaction with event listeners and the user input with some storage method.
Your_client-side_JS_script.js
function handle_submit(e) {
e.preventDefault();
if (e.target.id === 'addProduct') {
// When they click add product, you need to either pass their user details to the route and send them with the $.ajax GET request
//... and keep track of the data like that
// OR
// track that data in a cookie,
read up on cookies https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
} else if (e.target.id === 'newForm') {
console.log("Submit Form");
}
};
$('#addProduct').on('click', handle_submit);
$('#newForm').on('submit', handle_submit);
I recommend the cookie method. You set the cookie once, use it when you need it, then delete it when you're done.
With the first method, you have to send the data in your fetch (which doesn't need that data to get the products), then you have to manage that user_data throughout your back-end making sure it doesn't get lost. It's too much work. Use the cookie method instead.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to pull in specific values from a JSON File. I am attaching data to the component, which then gets passed through the getProjectsList function, which should then look for a specific JSON file and render that data within a list item.
This is my Component
class OpenProjectsHome extends React.Component {
constructor () {
super();
this.getProjectList = this.getProjectList.bind(this);
}
getProjectList(project) {
var projectNameFile = openProjectsData[project]
var url = window.location.protocol + "//" + window.location.host + "/open-projects/" + projectNameFile;
let clientName = "";
let projectName = "";
var startDate = "";
var component = this;
var jqxhr = $.get( url, function(myData) {
// console.log(myData)
console.log(myData[0].Client)
console.log(myData[0].Project)
console.log(myData[0].StartDate)
clientName = myData[0].Client
projectName = myData[0].Project
startDate = myData[0].StartDate
})
.fail(function() {
alert( "error" );
});
var projectURL = "project?=" + projectName;
return (
<li>
<a href={projectURL} title="">
<h6 className="eyebrow">{clientName}</h6>
<h6>{projectName}</h6>
<span><strong>Started:</strong> {startDate}</span>
</a>
</li>
)
}
render() {
return(
<section className="project-lists project-lists--current">
<div className="panel">
<div className="panel__header">
<h4 className="panel__title">Open Projects</h4>
</div>
<div className="panel__content">
<ul className="unordered-list">
{/* /////
///// WORKS
///// */}
{Object.keys(this.props.data).map(this.getProjectList)}
</ul>
</div>
</div>
</section>
);
}
}
Its rendering out the two <li> but my variables clientName, ProjectName, StartDate are all rendering as null within the return (the console.log within the $.get are working)
Any help would be greatly appreciated.
you should use setState and the axios and arrow function
var jqxhr =axios.get(url, (myData)=>{
// console.log(myData)
this.setState({
clientName : myData[0].Client,
projectName : myData[0].Project,
startDate = myData[0].StartDate
})
console.log(myData[0].Client)
console.log(myData[0].Project)
console.log(myData[0].StartDate)
})
.fail(function() {
alert( "error" );
});
axios doc https://github.com/axios/axios
in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..
Thanks & Regards
in Controller part :-
[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}
In view Part:-
$(document).ready(function () {
$('#FavouriteReports').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
data: { Columns: $('#FavouriteReports').val() },
datatype: "json",
traditional: true,
success: function (data) {
$('#SelectedFields').empty();
$.each(data, function (key, val) {
$('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
#Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { #class = "form-control editable" })
Let me assume Your model class Report
public class Report {
public int ReportId { get; set; }
public Name ReportName { get; set; }
}
Inside your ajax method
if(data!=null) {
$('#SelectedFields').empty();
var dd = null ;
$.each(data, function (key, val) {
dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
});
//append to given id
$('#SelectedFields').append(dd);
}
I hope this will help your, bind your dropdown list
Hy, I'm stuck with this error message and I can not find an solution.
I get this message error in the Knockout JavaScript library v2.2.0:
Unhandled exception at line 1053, column 5 in
localhost:port/Scripts/knockout-2.2.0.debug.js 0x800a138f -
Microsoft JScript runtime error: Invalid operand to 'in': Object
expected If there is a handler for this exception, the program may be
safely continued.
It stops at this line of code in knockout-2.2.0.debug.js
if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
I use this WebApi:
public class ProductsController : ApiController
{
IEnumerable<Product> products = new List<Product>()
{
new Product { Id = 1, Name = "Tomato_Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts(){
return products.AsEnumerable(); }
The scripts that I use are in a header section
#section Testscripts
{
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
}
And the Knockout code in the footer default script section
#section scripts
{
<script type="text/javascript">
var apiUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observableArray(data.Price);
this.Category = ko.observable(data.Category);
}
function ProductViewModel() {
var self = this;
self.myproducts = ko.observableArray([]);
$.getJSON(apiUrl, function (allData) {
var mappedProducts = $.map(allData, function (item) { return new Product(item) });
self.myproducts(mappedProducts);
});
};
ko.applyBindings(new ProductViewModel);
}
and show the data in body:
<ul data-bind="foreach: myproducts">
<li>
<input data-bind="value: Id" />
<input data-bind="value: Name" />
<input data-bind="value: Category" />
<input data-bind="value: Price" />
</li>
</ul>
The bug is in your Product function.
You want to create an ko.observableArray from data.Price which is a decimal value and not an array of values, which results in this not so nice exception.
Change to ko.observable and it should work:
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observable(data.Price);
this.Category = ko.observable(data.Category);
}