How to pass 2 parameters through $.getJson in MVC? - asp.net-mvc-4

I am doing my application in MVC. I did cascading dropdownlist in list . While selecting the value from dropdown i passed the value by $.getJson() to the controller. I am passing one id to the controller. My problem is i need to pass 2 id's to the controller. Is it possible to send 2 ids to the controller?
My View page is
<div>
#Html.DropDownList("Business", ViewBag.CategoryID as SelectList ,"Select the Business Category", new { id = "Business" })
</div>
<div>
<label>Select the Service Type</label>
#*<select id="Buname" name="buname" style="width:150px"></select>*#
#Html.DropDownList("Service", ViewBag.Service as SelectList,"Select", new { id = "Service", name ="buname"})
</div>
<div>
<label> Select the Location</label>
<select id="Location" name="location" style="width:150px"></select>
</div>
<div>
<label> Select the Location</label>
<select id="Employee" name="employee" style="width:150px"></select>
</div>
<script type="text/javascript">
$(function () {
$('#Business').change(function () {
$.getJSON('/Appt/Categories/' + $('#Business').val(), function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});
});
$('#Service').change(function () {
$.getJSON('/Appt/Location/' + $('#Service').val(), function (data) {
var items = '<option> Any Location </option>';
$.each(data, function (i, location) {
items += "<option value='" + location.Value + "'>" + location.Text +
"</option>";
});
$("#Location").html(items);
});
});
$('#Location').change(function () {
$.getJSON('/Appt/Employee/' + $('#Location').val(), function (data) {
var items = '<option> Any Employee </option>';
$.each(data, function (i, employee) {
items += "<option value='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#Employee").html(items);
$("Service").html(items);
});
});
});
</script>
My Controller code is
public ActionResult WaitingList()
{
SYTEntities ca = new SYTEntities();
ViewBag.CategoryId = new SelectList(ca.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(ca.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
return View();
}
public JsonResult Categories(int id)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Location(int id)
{
SYTEntities db = new SYTEntities();
var location = from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc;
return Json(new SelectList(location.ToArray(), "LocationId", "LocationName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id && s.BusinessID == 91
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
In public JsonResult Employee(int id) i need to pass ('#Service') value.
Is it possible to do? Can anyone please help me?

You can pass as many values as you want using the data parameter of jQuery.getJSON
var url = '#Url.Action("Categories", "Appt")'; // don't hard code your urls!
$.getJSON(url, { id: $('#Business').val(), otherProperty: anotherValue }, function (data) {

Yes you just need to add one more parameter to the Controller Action as below.
public JsonResult Categories(int id, int id2)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
and the below change in you View
$.getJSON('/Appt/Categories/' + $('#Business').val(), { id2: ('#otherId2').val() }, function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});

Related

Update Cascading Dropdown in Mvc5

Hi i want to know how to update or edit cascading dropdown like (Country,state,City)in mvc5.I have created 3 cascading dropdowns Country State city.If i select Country State will append in state dropdownn like wise city. Now i save these 3 dropdown values in table successfully. But now i stuck with edit option. I donno how to bind the saved value to these dropdowns in edit from.
My model
public class UCustomerManagementViewModel
{
public string UCountry { get; set; }
public string UState { get; set; }
public string UCity { get; set; }
}
My Controller code
public JsonResult GetCountries()
{
var Countries = db.Countries.ToList();
return Json(Countries, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryID(string countryId)
{
int id = Convert.ToInt32(countryId);
var states = db.States.Where(d => d.CountryID == id).Select(e => new { e.UID, e.StateName }).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCityByStateID(string stateId)
{
int id = Convert.ToInt32(stateId);
var Cities = db.Cities.Where(d => d.StateID == id).Select(e => new { e.UID, e.CityName }).ToList();
return Json(Cities, JsonRequestBehavior.AllowGet);
}
public ActionResult Update(int id)
{
CustomerManagement cc = db.CustomerManagements.Find(id);
ViewBag.CountryID = new SelectList(db.Countries.Where(d => d.CountryID.ToString() == cc.Country.ToString()), "CountryID", "CountryName",cc.CountryID);
var ucusmanvm = new UCustomerManagementViewModel();
ucusmanvm.UCountry = cc.Country;(here i get value 1)
ucusmanvm.UState = cc.State;(here i get value 2)
ucusmanvm.UCity = cc.City;(here iget value 2)
return View(ucusmanvm);
}
here i pass all the value to view form
My View Code
$(document).ready(function () {
debugger;
$.ajax({
type: "GET",
url: '#Url.Action("GetCountries", "FrmCustomerManagement")',
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryID + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
debugger;
$('#dropdownState').empty();
var cval = $('#dropdownCountry').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetStatesByCountryID", "FrmCustomerManagement")',
datatype: "Json",
data: { countryId: cval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.UID + '">' + value.StateName + '</option>');
});
}
})
});
$('#dropdownState').change(function () {
debugger;
$('#dropdownCity').empty();
var sval = $('#dropdownState').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetCityByStateID", "FrmCustomerManagement")',
datatype: "Json",
data: { stateId: sval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCity').append('<option value="' + value.UID + '">' + value.CityName + '</option>');
});
}
})
});
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #class = "form-control", #width = "80%", #value=Model.UCountry})
<div class="col-sm-8">
<label>State</label>
#Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { #class = "form-control", #width = "80%" , #value=Model.UState})
</div>
<div class="col-sm-8">
<label>City</label>
#Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select a City", new { #class = "form-control", #width = "80%" , #value=Model.Ucity})
</div>
Here in update from also i acheive Cascading dropdown using ajax. but in update form i donno how to bring the save value to drop downs(Country city, state) from controller to view (eg i saved UAE in Country Dropdown but in edit mode i donno how to bring UAE value in Country dropdown ).I passed value from controller but i donno how to bind that value in view.please any one help me to resolve this issue .

Calling HttpGet Method Using Ajax on IpagedListPager Mvc

I want to call HttpGet method on every page using ajax using IpagedList in MVC
Controller [HttpGet]
public ActionResult TestStarted(int TestId,DateTime End_Time,int page=1)
{
ViewBag.ct = 0;
ViewBag.TestId = TestId;
var Questions = GetNoOfQuestions().ToList();
ViewBag.Questions = Questions;
EAssessmentNew.BAL.StudentBal studBal = new EAssessmentNew.BAL.StudentBal();
EAssessmentNew.Dal.Student_Answer_Master _studAnsdal = new EAssessmentNew.Dal.Student_Answer_Master();
String TestName = studBal.FetchTestName(TestId);
ViewBag.TestName = TestName;
ViewBag.EndTime = End_Time;
List<Question> model = new List<Question>();
model = new Test_Planning().Fetch_Question_By_Test(TestId);
ViewBag.total = model.Count();
if (Request.QueryString["cnt"] != null)
{
int count = Convert.ToInt16(Request.QueryString["cnt"].ToString());
List<int> ChkOptions = studBal.GetCheckedAnswers((int)TestId, model[count].QuestionId, (int)(studBal.getStudentId(Session["sname"].ToString())));
ViewBag.ChkOptions = ChkOptions;
int cnt = 0;
if (ChkOptions.Count() != 0)
{
for (int i = 0; i < model[count].Options.Count(); i++)
{
if (model[count].Options[i].OptionId == ChkOptions.ElementAt(cnt))
{
model[count].Options[i].IsChecked = true;
cnt++;
}
else
{
model[count].Options[i].IsChecked = false;
}
if (cnt >= ChkOptions.Count() - 1)
{
cnt = ChkOptions.Count() - 1;
}
}
}
return View(model.OrderByDescending(v => v.Question_Id).ToPagedList(page, 1));
}
else
{
return View(model.OrderByDescending(v => v.Question_Id).ToPagedList(page, 1));
}
}
My View
<script type="text/javascript">
var TestId ='#ViewBag.TestId'
function loadQuestions() {
alert("ok")
$.ajax({
url: '#Url.Action("Student","TestStarted")',
data: { TestId:TestId },
contentType:"application/json",
success:function(responce){
}
});
}
</script>
<div class="pagedList">
#Html.PagedListPager(Model, page => Url.Action( "",new { onclick="loadQuestions()"}), PagedListRenderOptions.TwitterBootstrapPager)
</div>
I have done paging using IpagedList i want to call HttpGet Method Of controller on each and every page but i want this to perform without page refresh i have written ajax for it now i just want to know how can i call that ajax method using #Html.PagedListPager and on onClick event
Just Correct your url in ajax request as :
Instead of this
url: '#Url.Action("Student","TestStarted")'
It should be this
url: '#Url.Action("TestStarted","Student")'
and #Html.PagedListPager produces 'anchor' tag in html so you can put a click event on document as shown :-
$(document).on('click', 'a', function() {
$.ajax({
url: this.href,
type: 'GET',
datatype: "html",
data :{ TestId : $("#TestId").val(), End_Time :$("#End_Time").val(), page :$("#page").val() }
cache: false,
success: function(result) {
$('#results').html('');
$('#results').html(result);
}
});
return false;
});
In above code click event binds with every 'anchor' tag so if you need for specific 'anchor' tags then you can specify class as $(.pager).on('click', 'a', function() {}) and here '#results' is the target div id whose html is coming from controller action in your case this id may be different.

getting the error while copying feature ""Requested type name "feature" is unknown.""

This is code what I wrote for this...
Feature Deep Copy
rally.PortfolioItemDeepCopy = function (rallyDataSource, config) {
var portfolioitemBuffer = [];
var firstPortfolioItem = null;
var firstStory = null;
var finishedCallback;
var that = this;
//dojo.connect(obj, event, context, method, dontFix);
this._fireEvent = function(eventName, eventArgs) {
if (config && config.eventListeners[eventName] && dojo.isFunction(config.eventListeners[eventName])) {
config.eventListeners[eventName](that, eventArgs);
}
};
// removes private and read only fields to keep from pushing them up.
this.filterObject = function (object) {
return object;
};
this._addObject = function(object, typeName, callback) {
var item = dojo.clone(object);
item = this.filterObject(item);
function errorFunctionWrapper(error) {
if (dojo.isArray(error.Errors)) {
var errorMessage = error.Errors.pop();
if (errorMessage.indexOf("Not authorized to create:") >= 0) {
errorMessage = "Unable to create an object. This can happen due to a child or task being in a project you do not have write permissions to.";
}
rally.sdk.ui.AppHeader.showMessage("error", errorMessage, 10000);
}
else if(dojo.isObject(error)&&error.message){
rally.sdk.ui.AppHeader.showMessage("error", error.message, 10000);
error = [error.message];
}
if (dojo.isFunction(config.onError)) {
config.onError(error);
}
}
rallyDataSource.create(typeName, item, callback, errorFunctionWrapper);
};
this._copyAllFromBuffer = function() {
if (portfolioitemBuffer.length > 0) {
var portfolioitem = portfolioitemBuffer.pop();
that._copyPortfolioItem(portfolioitem.ref, portfolioitem.parent, that._copyAllFromBuffer);
}
else {
if (finishedCallback) {
finishedCallback(firstPortfolioItem);
}
}
};
this._addPortfolioItemsToBuffer = function(portfolioitemArray, parentRef) {
dojo.forEach(portfolioitemArray, function (portfolioitem) {
portfolioitemBuffer.push({
ref: portfolioitem._ref,
parent: parentRef
});
});
};
this._copyPortfolioItem = function(ref, parentRef, callback) {
rallyDataSource.getRallyObject(ref, function (foundObject) {
var type = "feature"
that._fireEvent("portfolioitemPreAdd", {portfolioitem:foundObject});
if (parentRef) {
foundObject.Parent = parentRef;
}
else {
foundObject.Name = "(Copy of) " + foundObject.Name;
}
that._addObject(foundObject, type, function (portfolioitemRef) {
if (!firstPortfolioItem) {
firstPortfolioItem = portfolioitemRef;
}
that._fireEvent("portfolioitemPostAdd", {});
that._addPortfolioItemsToBuffer(foundObject.Children, portfolioitemRef);
that._copyStoriesToPortfolioItem(foundObject.Stories, portfolioitemRef, callback);
that._copyTasksToStory(foundObject.Tasks, portfolioitemRef, callback);
}, null);
});
};
this._copyTasksToStory = function(tasks, storyRef, callback) {
//Copy the array
var localTasks = tasks.slice(0);
if (localTasks.length > 0) {
var task = localTasks.pop();
that._copyTask(task._ref, storyRef, function () {
that._copyTasksToStory(localTasks, storyRef, callback);
});
}
else {
callback();
}
};
this._copyStoriesToPortfolioItem = function(stories, portfolioitemRef, callback) {
//Copy the array
var localStories = stories.slice(0);
if (localStories.length > 0) {
var task = localStories.pop();
that._copyStory(story._ref, portfolioitemRef, function () {
that._copyStoriesToPortfolioItem(localStories, portfolioitemRef, callback);
});
}
else {
callback();
}
};
this._copyStory = function(ref, portfolioitemRef, callback) {
rallyDataSource.getRallyObject(ref, function (foundObject) {
var type = "hierarchicalrequirement";
foundObject.WorkProduct = portfolioitemRef;
that._fireEvent("storyPreAdd", {story:foundObject});
that._addObject(foundObject, type, function (ref, warnings) {
if (callback) {
that._fireEvent("storyPostAdd", [ref]);
callback();
}
}, null);
});
};
this._copyTask = function(ref, storyRef, callback) {
alert('helooooddddddddddddd task', ref);
rallyDataSource.getRallyObject(ref, function (foundObject) {
var type = "task";
foundObject.WorkProduct = storyRef;
that._fireEvent("taskPreAdd", {task:foundObject});
that._addObject(foundObject, type, function (ref, warnings) {
if (callback) {
that._fireEvent("taskPostAdd", [ref]);
callback();
}
}, null);
});
};
this.copyPortfolioItem = function (ref, callback) {
alert('hello');
that._copyPortfolioItem(ref, undefined, that._copyAllFromBuffer);
finishedCallback = callback;
};
};
</script>
<style type="text/css">
/* Add app styles here */
</style>
<script type="text/javascript">
rally.addOnLoad(function() {
var selectedValue = null;
var tasksAdded = 0;
var storiesAdded = 0;
var portfolioitemAdded = 0;
var searchPortfolioItem;
var searchStories;
var goButton, chooseButton;
var chooser;
var waiter;
var dataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
function taskPostAdd(object, args) {
tasksAdded = tasksAdded + 1;
displayTasksAdded(tasksAdded);
}
function taskPreAdd(object, args) {
dojo.byId("currentInfo").innerHTML = "Adding Task " + args.task.FormattedID + " - " + args.task.Name;
}
function storyPreAdd(object, args) {
dojo.byId("currentInfo").innerHTML = "Adding User Story " + args.story.FormattedID + " - " + args.story.Name;
}
function storyPostAdd(object, args) {
storiesAdded = storiesAdded + 1;
displayStoriesAdded(storiesAdded);
}
function displayStoriesAdded(count) {
dojo.byId("storyResult").innerHTML = "Stories added: " + count;
}
function portfolioitemPreAdd(object, args) {
dojo.byId("currentInfo").innerHTML = "Adding PortfolioItem " + args.story.FormattedID + " - " ;
}
function portfolioitemPostAdd(object, args) {
portfolioitemsAdded = portfolioitemsAdded + 1;
displayPortfolioItemsAdded(portfolioitemsAdded);
}
function displayPortfolioItemsAdded(count) {
dojo.byId("portfolioitemResult").innerHTML = "PortfolioItems added: " + count;
}
function displayTasksAdded(count) {
dojo.byId("taskResult").innerHTML = "Tasks added: " + tasksAdded;
}
function portfolioitemCopied(portfolioitem) {
dojo.byId("currentInfo").innerHTML = "Copy complete: ";
var link = new rally.sdk.ui.basic.Link({
item: portfolioitem,
text: portfolioitem._refObjectName
});
link.display('currentInfo');
goButton.setEnabled(true);
chooseButton.setEnabled(true);
if(waiter) {
waiter.hide();
waiter = null;
}
}
function buttonPressed() {
if (selectedValue) {
var config = {
eventListeners:{
portfolioitemPreAdd:portfolioitemPreAdd,
portfolioitemPostAdd:portfolioitemPostAdd,
storyPreAdd:storyPreAdd,
storyPostAdd:storyPostAdd,
taskPreAdd:taskPreAdd,
taskPostAdd:taskPostAdd
}
};
portfolioitemsAdded = 0;
displayPortfolioItemsAdded(portfolioitemsAdded);
tasksAdded = 0;
displayTasksAdded(tasksAdded);
storiesAdded = 0;
displayStoriesAdded(storiesAdded);
dojo.byId("currentInfo").innerHTML = "";
var copy = new rally.PortfolioItemDeepCopy(dataSource, config);
goButton.setEnabled(false);
chooseButton.setEnabled(false);
waiter = new rally.sdk.ui.basic.Wait({});
waiter.display('wait');
copy.copyPortfolioItem(rally.sdk.util.Ref.getRelativeRef(selectedValue), portfolioitemCopied);
}
}
function onChooserClose(chooser, args) {
if (args.selectedItem) {
selectedValue = args.selectedItem;
goButton.setEnabled(true);
dojo.byId('portfolioitemBox').innerHTML = args.selectedItem.FormattedID + ' - ' + args.selectedItem.Name;
}
}
function showChooser() {
var chooserConfig = {
fetch:"FormattedID,Name,Description",
type: "PortfolioItem",
title: "Feature Chooser"
};
chooser = new rally.sdk.ui.Chooser(chooserConfig, dataSource);
chooser.addEventListener('onClose', onChooserClose);
chooser.display();
}
rally.addOnLoad(function () {
goButton = new rally.sdk.ui.basic.Button({
text: "Copy",
enabled: false
});
goButton.addEventListener('onClick', buttonPressed);
goButton.display('goButton');
chooseButton = new rally.sdk.ui.basic.Button({
text: "Choose"
});
chooseButton.addEventListener('onClick', showChooser);
chooseButton.display('chooseButton');
showChooser();
rally.sdk.ui.AppHeader.setHelpTopic("252");
});
});
</script>
</head>
<body>
<div id="container">
<div style="float:left">
<span id="chooseButton"></span>
<span id="portfolioitemBox" style="line-height:18px;vertical-align:middle">[No feature selected]</span>
<span id="goButton"></span>
</div>
<div id="wait" style="float:left; height: 16px; width: 24px;"></div>
<div style="margin-left:5px;padding-top:10px;clear:both">
<div id="currentInfo" style="height:16px"></div>
<div id="portfolioitemResult" style="margin-top:10px"></div>
<div id="storyResult"></div>
<div id="taskResult"></div>
</div>
</div>
</body>
</html>
In WS API there is no object "feature". Please try either portfolioitem/feature or portfolioitem and then filter out by _type, e.g.
if(results.pi[i]._type == "PortfolioItem/Feature"){ //...
as shown here.
Since you are using a legacy AppSDK1 I assume you are setting a version to 1.43 as mentioned in this post.

Get dropdown value and text in controller mvc4 razor

I am working on MVC4 project. I have form where dropdownlist is populated with text and value field.
#Html.DropDownList("SourceDropDownList", new SelectList(""), "-Select-", new { #class = "validate[required]" })
This dropdown is populated from other dropdown change event
here is that code
function OnSourceFacilityDropDownChange(source, e) {
$("#SourceDropDownList").empty();
var curOpt = new Option('-Select-', "");
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
if (source.value != '') {
var url = getUrl() + '/AdminPanel/GetIns/?id=' + Math.random();
$.ajax({
url: url,
data: { clientid: $("#SourceDropDown").val(), strFacility: source.value }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
$.each(data, function (index, item) {
var curOpt = new Option(item.T, item.T);
curOpt.setAttribute("title", item.T);
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
});
},
error: function (request, status, error) { alert("Status: " + status + "\n Exception Handling : \n" + request.responseText); },
complete: function () {
$("#divLoading").hide();
}
});
}
else {
}
}
and code in AdminPanel/GetIns controller is
public JsonResult GetInspection(int clientid, string strFacility)
{
var objlist = (from d in Context.tbl_insp
orderby d.str_insp ascending
where d.clientid.Equals(ClientId))
select new { T= d.str_inspname, V= d.dte_start.Value.ToShortDateString()}).ToArray();
Array InspectionList = objlist;
return Json(InspectionList, JsonRequestBehavior.AllowGet);
}
And in model class i have initialized the property of dropdown
public string SourceDropDownList{ get; set; }
now i am getting only text values of what i select in SourceDropDownList dropdown..
How do i get the value also ??
Try with this,Just Example
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
#Html.DropDownList("CustomerNameId", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Script
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").change(function () {
var Id = $("#CustomerId").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { CustomerNameId: Id },
success: function (listItems) {
var STSelectBox = jQuery('#CustomerNameId');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
Controller
public JsonResult GetCustomerNameWithId(string CustomerNameId)
{
int _CustomerNameId = 0;
int.TryParse(CustomerNameId, out _CustomerNameId);
var listItems = GetCustomerNameId(_CustomerNameId).Select(s => new SelectListItem { Value = s.CID.ToString(), Text = s.CustomerName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public int CustomerNameId { get; set; }
}

Codeigniter get random record with limit

I've created a page that load 4 products everytime you scroll down the page with codeigniter and Ajax.
I followed this tutorial for create pagination with codeigniter and jQuery.Everything works fine, moreover I've changed the load type from database using Ajax.
I've got a problem with codeigniter.
When I try to get random record from the table I've got duplicate products.
This is the functions in codeigniter:
UPDATE CONTROLLER
function index()
{
$this->load->helper('url');
$data['description'] = "Description";
$data['keywords'] = "Keywords";
$data['products'] = $this->abitainterni->getAllProductsLimit();
$data['get_products'] = $this->abitainterni->get_products();
$this->load->view('welcome', $data);
}
function get_products($offset)
{
$already_used = $this->input->post('already_used');
$already = explode(',', $already_used);
$data['products'] = $this->abitainterni->getAllProductsLimit($offset, $already);
$arr['view'] = $this->load->view('get_products', $data, true);
$bossy = '';
foreach($data['products'] as $p) {
$bossy .= $p->productID.',';
}
$arr['view'] = $bam;
$arr['ids'] = $bossy;
echo json_encode($arr);
return;
}
UPDATE SCRIPT
<script type="text/javascript">
$(document).ready(function(){
<?
$like_a_boss = "";
foreach($products as $gp):
$like_a_boss .= $gp->productID.',';
endforeach;
?>
var products = '<?= $like_a_boss; ?>';
var loaded_products = 0;
$(".loadMoreProducts").click(function(){
loaded_products += 4;
var dati = "welcome/get_products/" + loaded_products;
$.ajax({
url:'welcome/get_products/' + loaded_products,
type: 'post',
data: {already_used: products},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
$("#mainContainerProductWelcome").append(obj.view);
already_used += obj.ids;
if(loaded_products >= products - 4) {
$(".loadMoreProducts").hide();
} else {
// load more still visible
}
},
error: function() {
// there's something wrong
}
});
// show spinner on ajax request starts
$(".loading-spinner").ajaxStart(function(){
$(".loading-spinner").show();
$(".text-load").hide();
});
// ajax request complets hide spinner
$(".loading-spinner").ajaxStop(function(){
$(".loading-spinner").delay(5000).hide();
$(".text-load").show();
});
return false;
});
// submit form contact
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// click on load more btn
$(".loadMoreProducts").click();
return false;
}
});
});
</script>
you'll need to keep track of the products you've already queried, throw their id's in an array, and then use something like a where not in. So something like this:
function getAllProductsLimit($offset=0, $already_used = array(0))
{
$this->db->order_by('productID', 'RANDOM');
$this->db->where_not_in('productID', $already_used);
$query = $this->db->get('product', 4, $offset);
if($query->num_rows() > 0){
return $query->result();
} else {
return 0;
}
}
NEW CONTROLLER
function index()
{
$this->load->helper('url');
$data['title'] = "Scopri i nostri prodotti";
$data['description'] = "Description";
$data['keywords'] = "Keywords";
$data['products'] = $this->abitainterni->getAllProductsLimit();
$data['get_products'] = $this->abitainterni->get_products();
$this->load->view('welcome', $data);
}
function get_products($offset)
{
$already_used = $this->input->post('already_used');
$already = explode(',', $already_used);
$data['products'] = $this->abitainterni->getAllProductsLimit($offset, $already);
$arr['view'] = $this->load->view('get_products', $data, true);
$bossy = '';
foreach($data['products'] as $p)
{
$bossy .= $->productID.',';
}
$arr['view'] = $bam;
$arr['ids'] = $bossy;
echo json_encode($arr);
return;
}
NEW SCRIPT
<script type="text/javascript">
$(document).ready(function(){
<?
$like_a_boss = '';
foreach($get_products as $gp):?>
$like_a_boss .= $gp->productID.',';
endforeach;?>
var products = '<?= $like_a_boss; ?>';
var loaded_products = 0;
$(".loadMoreProducts").click(function(){
loaded_products += 4;
var dati = "welcome/get_products/" + loaded_products;
$.ajax({
url:'welcome/get_products/' + loaded_products,
type: 'post',
data: {already_used: products},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
$("#mainContainerProductWelcome").append(obj.view);
already_used += obj.ids;
if(loaded_products >= products - 4) {
$(".loadMoreProducts").hide();
} else {
// load more still visible
}
},
error: function() {
// there's something wrong
}
});
// show spinner on ajax request starts
$(".loading-spinner").ajaxStart(function(){
$(".loading-spinner").show();
$(".text-load").hide();
});
// ajax request complets hide spinner
$(".loading-spinner").ajaxStop(function(){
$(".loading-spinner").delay(5000).hide();
$(".text-load").show();
});
return false;
});
// submit form contact
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// click on load more btn
$(".loadMoreProducts").click();
return false;
}
});
});
</script>
Then whereever your using that function, before you echo out your results to your ajax function, run a quick foreach to add the ids of the products you just got to the already used array. You can either store this is session, or pass it back and forth between your ajax stuff, or if your ajax stuff is written fine, you don't need to worry about it, just attach the product id's to each product you're displaying using a data attribute or something and generate the array that way.