I am very much troubled by the thing, tat I am not able to store the user info for the next view. Here is my factory:
app.factory("currentUser", currentUser);
function currentUser() {
var profile = {
userId: "",
firstName: "",
lastName: "",
userEmailId: "",
userAccessToken: ""
};
var setProfile = function (data) {
profile.userId = "";
profile.firstName = data.userDetails.frstName;
profile.lastName = data.userDetails.lastName;
profile.userEmailId = data.Email;
profile.userAccessToken = data.userDetails.accessCode;
}
var getProfile = function () {
return profile;
}
return {
setProfile: setProfile,
getProfile: getProfile
}
}
I set the data using the function:
currentUser.setProfile(data);
But when in another controller I am trying to get the data I am getting blank object:
currentUser.getProfile();
Here is my routing
angular.module("angularModule", ["ngAnimate", "ui.router"])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
// catch all route
// send users to the form page
$locationProvider.html5Mode(true);
$stateProvider.state('Register', {
url: '/Register',
templateUrl: 'Templates/Registration.html',
controller: "Registration"
})
Please help me with the solution I need the solution at earliest.
var app = angular.module("MyApp", []);
app.factory("myService", function() {
var profile = {
userId: "",
firstName: "",
lastName: "",
userEmailId: "",
userAccessToken: ""
};
profile.setProfile = function(userDetails) {
profile.userId = "";
profile.firstName = userDetails.frstName;
profile.lastName = userDetails.lastName;
profile.userEmailId = userDetails.userEmailId;
profile.userAccessToken = userDetails.accessCode;
}
profile.getProfile = function() {
return profile;
}
return profile;
});
app.controller("ctrl1", ["$scope", "myService", function($scope, myService) {
$scope.profile = {
userId: "1233",
firstName: "JOHN",
lastName: "DOE",
userEmailId: "",
userAccessToken: "314wdw"
};
myService.setProfile($scope.profile);
$scope.valueA = myService.getProfile();
}]);
app.controller("ctrl2", ["$scope", "myService", function($scope, myService) {
$scope.valueB = myService.getProfile();
}]);
DEMO
Related
I want to be able to return json object with a custom error/success message using the same line of code on post request: i have these two lines of code:
return Json(data);
return Json(new { f = "error" });
I want to be able display it in one line like this:
return Json(data, Json(new { f = "error" }));
I know i can't have multiple return statements in my code. but i want to return the data with message.
My ServerSide Code:
if (getId > 0)
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { s = "success" });
}
else
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { f = "error" });
}
My Ajax Fucntion:
<script type = "text/javascript">
$(document).ready(function () {
$('#tblAppointment').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
});
var table = $("#tblAppointment").DataTable();
$("#saveButton").click(function () {
console.log("appDate:" + $('.datetimepicker').val());
$.ajax({
url: '/Appointment/InsertPatientAppointment/',
type: "POST",
data: JSON.stringify({
appointmentDate: $(".datetimepicker").val(),
patientRegNo: $("#patientRegNo").val(),
reasons: $("#reasons").val()
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Failed!",
text: _data.f, //"Ooops! something went wrong,
record not saved,
try again later ",
type: "info"
});
table.clear().draw();
//table.destroy();
// $("#viewReportBtn").prop("disabled", false);
return false;
} else {
swal({
title: "Success!",
text: _data.s, //"Appointment added successfully!",
type: "success"
});
}
$(".datetimepicker").val('');
$("#patientRegNo").val('');
$("#reasons").val('');
var arr = $.map(JSON.parse(_data), function (el) {
return
el
});
if (arr.length === 0) {
swal({
title: "No Record Found!",
text: _data.f, //"Your search returns an empty
result set !",
type: "info"
});
table.clear().draw();
return false;
}
table.clear();
table.destroy();
$('#tblAppointment').dataTable({
data: arr,
columns: [{
"data": "MatricRegNo"
},
{
"data": "PatientName"
},
{
"data": "EntryDate"
},
{
"data": "AppointmentDate"
},
{
"data": "Reasons"
},
{
"data": function (data, type, row, meta) {
return '<span class="fa fa-edit" data-
toggle = "modal"
data - target = "#modal-Edit" > < /span>';
}
}
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'Portriat',
pageSize: 'A4'
}
]
});
table = $("#tblAppointment").DataTable();
}
});
});
});
</script>
You can use this:
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
var returnData = new object[2];
returnData[0] = data;
returnData[1] = new { f = "error" };
return Json(returnData);
You can integrate the data object in your anonymous object which you are already returning:
return Json(new {data = data, f = "error"});
If you do it like this, you can access the data object in your ajax call like this:
success: function (_data) {
var returnedData = _data.data;
}
Which means you have to adjust your map method call where you are preparing the data array for the table. Instead of:
var arr = $.map(JSON.parse(_data), function (el) { return el });
call it with the data object _data.data:
var arr = $.map(JSON.parse(_data.data), function (el) { return el });
This should do the trick.
I would potentially approach in the following manner, extend the JsonResult to include a status code. This way you can dictate the level of success to the Ajax request.
public class JsonResultWithStatusCode : JsonResult
{
private readonly HttpStatusCode statusCode;
public JsonResultWithStatusCode(object data, HttpStatusCode statusCode)
{
Data = data;
this.statusCode = statusCode;
}
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.StatusCode = (int)statusCode;
base.ExecuteResult(context);
}
}
Then inside your controller:
if(...)
{
var model = JsonConvert.SerializeObject(...);
return new JsonResultWithStatusCode(model, HttpStatusCode.Ok)
}
else
{
var model = new { error = "..." };
return new JsonResultWithStatusCode(model, HttpStatusCode.InternalServerError);
}
Then inside your Ajax you would be able to read the status code and then read the body.
.success: function(response) {
console.log(response.status); // Status Code (200 or 500 based on above)
console.log(response.data); // Our model based on above, one writing error the other actual model data.
}
All you would have to do would be read based on the server output.
I am using the following to generate a dropdownlist of provinces based on the country selection:
<select id="Province" name="Province" class="form-control input-sm">
#{
string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName = null;
}
#{
if (Model != null && !String.IsNullOrEmpty(Model.Province))
{
selectedProvinceName = Model.Province;
}
else
{
selectedProvinceName = ConfigData.DefaultProvinceName;
}
}
#foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName
? "selected=\"selected\""
: String.Empty;
<option value="#(anEntry)" #(selectedTextMark)>#(anEntry)</option>
}
</select>
The challenge is I don't have a list of provinces (states) for other countries! Is there a way to allow for the user to type in the name of the province? Like a combobox.
I had to do it using Knockout-Kendo combobox, here is the solution:
Controller:
public ActionResult Index()
{
ViewBag.CountryID = new SelectList(db.Countries, "ID", "Name", "34");
.....
public JsonResult GetState(int? id)
{
if (id == null)
{ id = 34; }
var data = db.States.Where(x => x.CountryID == id)
.Select( x =>
new
{
ID = x.ID,
Name = x.Name
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
In the View:
#Html.DropDownList("Country", ViewBag.CountryID as SelectList, "Select...",
new { onchange = "UpdateProvinces();" })
<input data-bind="kendoComboBox: { dataTextField: 'Name', dataValueField: 'ID',
data: choices, value: selectedChoice }" />
Here is the JavaScript:
function UpdateProvinces() {
var countryId = $("#Country option:selected").val();
$.getJSON("/Home/GetState/" + countryId,
null,
function (data) {
objVM.choices(data);
});
}
function ItemViewModel(arg) {
arg = 34;
var self = this;
this.choices = ko.observableArray([]),
$.ajax({
type: "GET",
url: '#Url.Action("GetState", "Home")',
contentType: "application/json; charset=utf-8",
data: { id: arg },
dataType: "json",
success: function (data) {
self.choices(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
var selectedChoice = {
ID: self.ID,
Name: self.Name
};
self.selectedChoice = ko.observable();
}
var objVM = new ItemViewModel();
ko.applyBindings(objVM);
Edit:
Another alternative is to use Telerik MVC UI Combobox http://demos.telerik.com/aspnet-mvc/combobox/cascadingcombobox
I am trying to load my typeahead.js by using bloohound's remote function where i can call my Web Method. I have seen similar threads where a querystring is being used :
Integrating Typeahead.js with ASP.Net Webmethod
Typeahead.js and Bloodhound.js integration with C# WebForms WebMethod
http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/
And many more....
However, i cannot find an example where ajax is used to call the webmethod from typeahead.js.
So this is what i have currently and it works:
WebMethod
[WebMethod]
public static string GetEmployeeTypeahead()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = 100000000;
string json;
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1)
.Select(x => new {
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToList();
json = jss.Serialize(result);
}
return json;
}
The Client
function LoadEmployeeJSON() {
$.ajax({
type: "POST",
url: "/WebMethods/Test.aspx/GetEmployeeTypeahead",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
empList = $.parseJSON(msg.d); //otherwise does not work
LoadEmployeeTypeahead();
},
error: function (msg) {
alert("error:" + JSON.stringify(msg));
}
});
}
function LoadEmployeeTypeahead() {
var empData = empList;
var fullname = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: empData,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}
function clearAndReInitilize() {
$('.typeahead').typeahead('destroy');
$('.typeahead').val('');
}
So as you can see i am making a local call instead of remote.
How can i get the remote function to call my webthod and fill the typeahead without using any querystrings
Okay finally got it to work via an ashx generic handler. So instead of using a web method i used the following ashx handler:
public class Employess : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = Int32.MaxValue;
string json;
string prefixText = context.Request.QueryString["query"];
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1 && x.FULLNAME.Contains(prefixText.ToUpper()))
.Select(x => new
{
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToArray();
json = jss.Serialize(result);
}
context.Response.ContentType = "text/javascript";
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Below is the jquery and the ajax call to the ashx handler
$(document).ready(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
LoadEmployeeTypeahead();
// LoadEmployeeJSON();
});
function LoadEmployeeTypeahead() {
//var empData = empList;
var fullname = new Bloodhound({
remote: {
url: '/Employess.ashx?query=%QUERY',
wildcard: '%QUERY'
},
datumTokenizer: function (d) {
//var employees = $.parseJSON(msg.d);
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.MANNO + "</em></span><span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}
i have my jquery like,
$(document).ready(function () {
$('#NotAllotedStudentsGrid').jtable({
title: 'Allot to Students below',
paging: true,
pageSize: 5,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkbo.xes on first column
actions: {
listAction: '#Url.Action("NotAllotedStudentsList")',
//deleteAction: '#Url.Action("DeleteStudent")',
//updateAction: '#Url.Action("UpdateStudent")',
//createAction: '#Url.Action("CreateStudent")'
},
fields: {
UserNo: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '15%'
},
Batch: {
title: 'Batch',
},
EmailAddress: {
title: 'Email address',
},
ContactNo: {
title: 'Contact No',
type: 'textarea',
}
}
});
//Load student list from server
$('#NotAllotedStudentsGrid').jtable('load');
$('#SearchFor').button().click(function () {
var SearchForValue = $("#NotAllotedStudentsList").val();
var StudentInputTypeValue = $("#InputType").val();
var options = {};
options.type = "POST";
options.url = "/Dashboard/NotAllotedStudentsList/";
options.data = JSON.stringify({ model: { SearchFor: SearchForValue, StudentInputType: StudentInputTypeValue } });
options.dataType = "json";
options.contentType = "application/json";
$.ajax(options);![enter image description here][1]
});
i have my controller like,
public ActionResult NotAllotedStudentsList(AllotQuestionSet model,int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
List<TutorStudentsGridModel> tutorStudentsGridModelList = new List<TutorStudentsGridModel>();
User userDetails = _sessionHelper.Get<User>(KrackemSessionConstants.UserDetails);
StudentResponse studentListResponse = new StudentResponse();
int questionSetNo = Int32.Parse(_sessionHelper.Get<string>(KrackemSessionConstants.QuestionSetNo));
if (model.SearchFor == null)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByTutorNo(studentRequest);
}
//Get Not Allotted Students By Name
if (model.SearchFor != null && model.StudentInputType == StudentInputType.Name)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo,
InputString = model.SearchFor
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByName(studentRequest);
}
foreach (StudentContract studentDetails in studentListResponse.StudentList)
{
TutorStudentsGridModel tutorStudentsGridModel = MappingEngineFactory.GetMappingEngine().Map<StudentContract, TutorStudentsGridModel>(
studentDetails);
tutorStudentsGridModel.Id = studentDetails.UserNo;
tutorStudentsGridModelList.Add(tutorStudentsGridModel);
}
if (jtSorting != null)
tutorStudentsGridModelList = ControllerHelper.SortList(jtSorting, tutorStudentsGridModelList);
tutorStudentsGridModelList = jtPageSize > 0 ? tutorStudentsGridModelList.Skip(jtStartIndex).Take(jtPageSize).ToList() : tutorStudentsGridModelList.ToList();
return Json(new { Result = "OK", Records = tutorStudentsGridModelList, TotalRecordCount = studentListResponse.StudentList.Count() });
}
Initially, the page with grid get loaded from server with the list of students with fields i.name ii.batch iii.email iv.contact_no, after selecting "name" from dropdown and entered a name in textbox then clicking the search button for search , the search results should display. But its displaying old grid. kindly tell me how to display the search result from the grid using jquery.
A selection on the first table results in change in the second table. However, the change occurs only once. Any subsequent calls do generate valid JSON but the html remains unchanged.
The Controller:
[HttpPost]
public JsonResult M1List(int jtStartIndex, int jtPageSize, string jtSorting)
{
try
{
List<tblM> m1 = new DataHelper().GetM1(jtSorting, jtPageSize, jtStartIndex);
int m1Count = new DataHelper().Getm1Count();
return Json(new { Result = "OK", Records = m1, TotalRecordCount = m1Count });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[HttpPost]
public JsonResult M2List(int mId, int jtStartIndex, int jtPageSize)
{
try
{
List<ViewM1A> m2 = new DataHelper().GetM2ForM1(mId.ToString(), "mId", jtPageSize, jtStartIndex);
int m2Count = new DataHelper().GetM2ForM1Count(mId.ToString());
return Json(new { Result = "OK", Records = m2, TotalRecordCount = m2Count });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
The JS:
$(document).ready(function () {
$('#m1TC').jtable({
paging: true,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: false, //Allow multiple selecting
actions: {
listAction: '#Url.Action("M1List")'
},
fields: {
mId: {
title: 'Id'
}
},
selectionChanged: function () {
var $selectedRows = $('#m1TC').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
buildM2Table(record.mId);
});
$('#m2TC').jtable('load');
}
});
$('#m1TC').jtable('load');
});
function buildM2Table(actionUrl) {
$('#m2TC').jtable({
paging: true,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
actions: {
listAction: '/Connections/M2List?mId=' + actionUrl
},
fields: {
FullName: {
title: 'Name'
},
},
selectionChanged: function () {
var $selectedRows = $('#m2TC').jtable('selectedRows');
$('#SelectedRowList').empty();
if ($selectedRows.length > 0) {
} else {
$('#SelectedRowList').append('No row selected! Select rows to see here...');
}
}
});
}
The html:
<div id="m1TC"></div>
<div id="m2TC"></div>
Solved by adding this code after 'var record = $(this).data("record");':
$('#m2TC').remove();
$('#m1TC').after('<div id="m2TC"></div>');