Cordova Contact with Database - c#

Below is my code which consist of Javascript and WebAPI,I am trying to check the local phone contacts with my Database.I am using Cordova Contact API to get all local phoneNumber and Name.I am storing phonenumber and name separately in two different array variable and passing that to WEBAPI through ajax has show in below code.In C# I am comparing local phonenumber with phoneNumber which is in database,If the phone number is exist in database i am keeping it in existUserContact variable,if the phone number is not exist in database i am keeping it in numbersThatNotExistsInDB variables.Now if phoneNumber exist it database i ll get username from database its working fine.But if the number is not exisit in database i need to bind the same name which is in local phoneContact name which i am getting from NameCollection to particular notexist Number.how i can bind particular name which i am stored in NameCollection for numbersThatNotExistsInDB kindly suggest
//cordova Contact API Success function//
function onSuccess(contacts) {
if (contacts.length != 0) {
// get formatted names and sort
for (var i = 0; i < contacts.length; ++i) {
if (contacts[i].name) {
if (contacts[i].name.formatted)
//Storing names in names array variable//
names.push(contacts[i].name.formatted.trim());
}
}
for (var i = 0; i < contacts.length; ++i) {
if (contacts[i].phoneNumbers) {
if (contacts[i].phoneNumbers[0].value)
//Storing phoneNumber in phoneNumberContactCollection array variable//
phoneNumberContactCollection.push(contacts[i].phoneNumbers[0].value); }
} }}
//Through ajax function i am passing my all phone numbers and names to webapi //
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({Names:names,mobileNumber: phoneNumberContactCollection, deviceUUID: self.DeviceUUID }),
url: serverUrl + 'xx/xxx/GetContacts',
success: function (data) { }
[HttpPost]
public IHttpActionResult GetContacts(JObject jsonData)
{
dynamic json = jsonData;
string deviceUID = json.deviceUUID;
string[] mobilenumber =json.mobilecollection.ToObject<string[]>();
string[]NameCollection= json.nameCollection.ToObject<string[]>();
var getContacts= xxx.getAllcontacts(mobilenumber,deviceUID,NameCollection);
return ok(getContacts);
}
public List<ContactList> getAllcontacts(string[]mobilenumberCollection, string deviceUID,string[] NameCollection)
{
try
{
List<ContactList> MobileContact = new List<ContactList>();
List<string> mobileNumbers = new List<string>();
List<string> ContactName = new List<string>();
if (deviceUID != null)
{
var existdevice = dbContext.DeviceInformation.FirstOrDefault(u => u.deviceUUID == deviceUID);
if (existdevice != null)
{
var existuser = dbContext.UserTable.FirstOrDefault(u => u.deviceID == existdevice.deviceId);
if (existuser.userId != 0 && existuser.IsActive == true && mobilenumberCollection != null)
{
foreach (var item in mobilenumberCollection)
{
mobileNumbers.Add(mobile);
}
}
foreach (var contactName in NameCollection)
{
ContactName.Add(contactName);
}
//Here i am checking the phoneNumbers which exist in Database
var existUserContact = dbContext.UserTable.Where(m => mobileNumbers.Contains(m.mobileNumber)).Distinct().ToList();
//Here the phoneNumbers which Not exist in Database
var numbersThatNotExistsInDB = mobileNumbers.Where(n => !existUserContact.Any(a => a.mobileNumber == n)).ToList();
if (existUserContact != null)
{
foreach (var MobileNumberExsitDB in existUserContact)
{
ContactList contactList = new ContactList();
if (existuser.userId!=MobileNumberExsitDB.userId)
{
contactList.userId = MobileNumberExsitDB.userId;
contactList.userName = MobileNumberExsitDB.userName;
contactList.userProfileImageBase64 = MobileNumberExsitDB.userImageBase64;
contactList.userProfileImagetype = MobileNumberExsitDB.userImagetype;
MobileContact.Add(contactList);
}
} }
}
if (numbersThatNotExistsInDB != null)
{
foreach (var NotExistnumber in numbersThatNotExistsInDB)
{
foreach (var NotExist in ContactName)
{
ContactList phonenumber = new ContactList();
phonenumber.mobileNumber = NotExistnumber;
phonenumber.userName = NotExist;
MobileContact.Add(phonenumber);
}
}
}
}
}
}
return MobileContact;
}
catch (Exception)
{
throw new Exception("Server Busy! Please try after some time. 309");
}
}

Related

Controller action called twice from Ajax post

It's been hours I'm searching for a solution.
I'm developing a C# and ASP.NET application using MVC.
It's a direct mail management application. I have a page that searches for duplicates in the companies database, then displays it in a list.
Then, when the user clicks on the company name, he lands on a page that displays the duplicates for this company.
To do so, on the search page I made an Ajax request to my controller action "Fiche", which will use the parameters sent to build the request and return the viewmodel filled with the company's duplicates.
The action is called once, with the right parameters, but then, it's called twice, with parameters set to false for the booleans and null for the string. So, I don't manage to retrieve the duplicates for the company.
Here is my click event :
$(a).click(function () {
//some code that sets the variables used in cc
var cc = {
rsoc: raison_sociale,
adr1: adresse,
cp: code_postal,
ville: ville_entreprise,
tel: telephone,
mail: e_mail,
user_id: code_cotisant,
profileConf: sessionStorage.getItem('categ')
}
$.ajax({
url: "#Url.Action("Fiche", "Doublons")",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ cc: cc, rsoc: $(this).text() }),
success: function(response) {
response ? alert("It worked!") : alert("It didn't work.");
}
});
})
Here is my controller action :
public ActionResult Fiche(CompareConfiguration cc, string rsoc)
{
bool categorie = cc.profileConf != null ? true : false;
Models.Entreprise entreprise = new Models.Entreprise();
DataTable dt_doublons = new DataTable();
if (rsoc != null)
{
dt_doublons = entreprise.search_doublons(cc.Rsoc, cc.Adr1, cc.CP, cc.Ville, cc.Tel, cc.Mail, cc.User_Id, categorie, cc.profileConf.Split(','));
for (int i = 0; i < dt_doublons.Rows.Count; i++)
{
if(rsoc != dt_doublons.Rows[i]["rsoc"].ToString())
{
dt_doublons.Rows[i].Delete();
}
}
dt_doublons.AcceptChanges();
}
return View(getDoublons(dt_doublons));
}
private DoublonsViewModel getDoublons(DataTable dt_doublons)
{
DoublonsViewModel dblVM = new DoublonsViewModel()
{
ListeDoublons = new List<EntrepriseAndContacts>(),
dt_doublons = dt_doublons
};
for (int i = 0; i < dt_doublons.Rows.Count; i++)
{
EntrepriseAndContacts eac = new EntrepriseAndContacts();
eac.Id = Convert.ToInt32(dt_doublons.Rows[i]["id_entreprise"]);
eac.Rsoc = dt_doublons.Rows[i]["rsoc"].ToString();
eac.nb_doublons = Convert.ToInt32(dt_doublons.Rows[i]["nb_doublons"]);
eac.Etat_entreprise = Convert.ToInt32(dt_doublons.Rows[i]["importee"]);
eac.Etat_contact = Convert.ToInt32(dt_doublons.Rows[i]["importe"]);
eac.User_id = dt_doublons.Rows[i]["user_id"].ToString();
eac.CVI = dt_doublons.Rows[i]["cvi"].ToString();
eac.Nom = dt_doublons.Rows[i]["nom"].ToString();
eac.Prenom = dt_doublons.Rows[i]["prenom"].ToString();
eac.Mail = dt_doublons.Rows[i]["mail"].ToString();
dblVM.ListeDoublons.Add(eac);
}
return dblVM;
}
And the link :
foreach (var doublon in Model.ListeDoublons)
{
<tr>
<td class="center size-15 height-25">
#doublon.Rsoc
</td>
<td class="center size-15 height-25">#doublon.nb_doublons</td>
</tr>
}
I tried to return false or to preventDefault on the click event but the view "Fiche" wasn't loaded anymore so it's not a solution in this case. I must be doing something wrong !
Edit : I've added [HttpPost] before my action but now the view isn't found.
Hope this time I can post an answer because I found a solution to my problem.
I removed the [HttpPost] before the action Fiche and while passing in the method for the first time, I stored the parameters cc and rsoc in two session variables. Then, I reassign it to cc and rsoc, so when it passes in the method for the second time with cc and rsoc empty, it retrieves them by the session. It's not a nice solution but I've got no time left and it works.
public ActionResult Fiche(CompareConfiguration cc, string rsoc)
{
if(cc.Adr1 != false || cc.Rsoc != false || cc.CP != false || cc.Ville != false || cc.Tel != false || cc.Mail != false || cc.User_Id != false)
{
Session["cc"] = cc;
Session["rsoc_entreprise"] = rsoc;
}
cc = (CompareConfiguration)Session["cc"];
rsoc = Session["rsoc_entreprise"].ToString();
bool categorie = cc.profileConf != null ? true : false;
Models.Entreprise entreprise = new Models.Entreprise();
DataTable dt_doublons = new DataTable();
if (rsoc != null)
{
dt_doublons = entreprise.search_doublons(cc.Rsoc, cc.Adr1, cc.CP, cc.Ville, cc.Tel, cc.Mail, cc.User_Id, categorie, cc.profileConf.Split(','));
for (int i = 0; i < dt_doublons.Rows.Count; i++)
{
if(rsoc != dt_doublons.Rows[i]["rsoc"].ToString())
{
dt_doublons.Rows[i].Delete();
}
}
dt_doublons.AcceptChanges();
}
return View(getDoublons(dt_doublons));
}

OpenXML not creating document on production, but fine in Dev

I have launched a new application at work. We create letters using OpenXML which works flawlessly on Dev, but on production the solution is not returning.
$("#createLetter").on("click", CreateLetter);
function CreateLetter() {
$.ajax({
type: "POST",
url: "/Letters/CreateLetter",
data: {
EntityType: "#overview.EntityType",
EntityId: #overview.EntityId,
Recipient: $("#Recipient").val(),
TemplatesLocation: $("#templatePath").val(),
SaveAs: $("#saveAs").val()
},
async: false,
success: openLetter
});
}
function openLetter(data) {
openFile(data);
window.location.reload(false);
}
Controller Method:
[ValidateInput(false)]
[HttpPost]
public JsonResult CreateLetter(CreateLetter input)
{
Recipient obj = logic.SplitRecipientInput(input.Recipient);
input.RecipientId = obj.RecipientId;
input.RecipientType = obj.Type;
input.Username = Helpers.GetLoggedInUser();
var x = logic.CreateLetter(input);
if (x.Success == 1)
{
return Json(x.Data, JsonRequestBehavior.AllowGet);
}
else
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
}
Consumption Logic:
public CreatedLetter CreateLetter(CreateLetter input)
{
CreatedLetter response = new CreatedLetter();
Parameters.Add("TemplatePath", GetApiValue(input.TemplatesLocation));
Parameters.Add("EntityType", GetApiValue(input.EntityType));
Parameters.Add("EntityId", GetApiValue(input.EntityId));
Parameters.Add("RecipientId", GetApiValue(input.RecipientId));
Parameters.Add("RecipientType", GetApiValue(input.RecipientType));
Parameters.Add("Username", GetApiValue(input.Username));
Parameters.Add("SaveAs", GetApiValue(input.SaveAs));
response = Api.WebRequest<CreatedLetter>("CreateLetters", Parameters, Method.POST) as CreatedLetter;
return response;
}
API Controller method:
[ActionName("CreateLetter")]
[HttpPost]
public ApiResponse CreateLetter(LetterCreateInput input)
{
try
{
LetterTemplateLogic logic = new LetterTemplateLogic();
Random r = new Random();
var randomId = r.Next(100000, 999999);
string fileName = string.Format("{0} - {1}", randomId, input.SaveAs);
input.SaveAs = fileName;
// Get all objects for Letter
List<object> objs = logic.TemplateObjectsRetriever(input.EntityId, input.EntityType, input.Username, randomId);
objs.Add(logic.GetRecipient(input.RecipientId, input.RecipientType));
// Get save location
string saveLocation = logic.LetterLocationResolver(input.EntityId, input.EntityType);
var data = logic.OpenAndUpdateTemplate(objs, input.TemplatePath, input.SaveAs, saveLocation, FileExtension);
AttachmentInput letterAttachment = new AttachmentInput();
letterAttachment.Id = input.EntityId;
letterAttachment.FileTypeId = 1;
letterAttachment.Path = data;
letterAttachment.Username = input.Username;
letterAttachment.Description = fileName;
letterAttachment.EntityType = input.EntityType;
logic.InsertLetterAttachment(letterAttachment);
return ApiResponse.Return(data);
}
catch (Exception ex)
{
return ApiResponse.Error(ex);
}
}
This returns literally nothing on production. No errors in the console, no errors from the API which logs erroneous calls. I was hoping someone could make a suggestion?
Thanks.

how to retrieve the count of a controller function to an ajax progress bar asp.net mvc

I am attempting to get a raw count from a foreach function inside of a result for an AJAX post response. The issue I am facing is that in my post response, I am receiving the total of all the iterations of the foreach, but not the individuals. The purpose of doing this is to show the progress of the upload by filling a progress bar at each iteration.
Controller:
public JsonResult progressFunction(int? SystemGeneralAnnouncementId)
{
var systemGeneralAnnouncement = (SystemGeneralAnnouncementId == null) ? null : _uow.SystemGeneralAnnouncementRepository.GetById(SystemGeneralAnnouncementId.Value);
List<Status> status = new List<Status>();
if (systemGeneralAnnouncement.Statuses.Length > 0)
{
status.AddRange(systemGeneralAnnouncement.Statuses.Split(',').Select(item => (Status) Enum.Parse(typeof (Status), item)));
}
var allPocEmailAddresses = new List<InstitutionPointOfContact>();
var pocEmailAddresses = new List<InstitutionPointOfContact>();
//retrieve all Point of contact based upon selected statuses per each loop
var result = new List<InstitutionPointOfContact>();
foreach (var item in status)
{
result = _uow.InstitutionPointOfContactRepository.GetAllByStatus(item).ToList();
allPocEmailAddresses.AddRange(result);
}
// Retrieve the poc email addresses based on the who is intended to receive the email message
if (systemGeneralAnnouncement.SendToRecipients.Contains("(1) All Three POCs"))
{
pocEmailAddresses = allPocEmailAddresses;
}
else
{
if (systemGeneralAnnouncement.SendToRecipients.Contains("(2) All POCs"))
{
pocEmailAddresses.AddRange(allPocEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.Primary).ToList());
}
if (systemGeneralAnnouncement.SendToRecipients.Contains("(3) All Compliance POCs"))
{
pocEmailAddresses.AddRange(allPocEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.Secondary).ToList());
}
if (systemGeneralAnnouncement.SendToRecipients.Contains("(4) All Authorities"))
{
pocEmailAddresses.AddRange(allPocEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.SigningAuthority).ToList());
}
if (systemGeneralAnnouncement.SendToRecipients.Contains("(5) All Rate POCs"))
{
pocEmailAddresses.AddRange(allPocEmailAddresses.Where(r => r.PointOfContactType == PointOfContactTypes.TuitionRates).ToList());
}
if (systemGeneralAnnouncement.SendToRecipients.Contains("(6) Specified Email Address"))
{
var pocs = new List<InstitutionPointOfContact>();
string[] emails = systemGeneralAnnouncement.EmailAddresses.Split(',');
foreach (string email in emails)
{
var addPoc = new InstitutionPointOfContact { Email = email };
User user = _uow.UserRepository.GetByEmail(email);
if (user == null)
{
addPoc.FirstName = "Not Created Account Yet";
}
else
{
addPoc.FirstName = user.FirstName;
addPoc.LastName = user.LastName;
}
List<InstitutionPointOfContact> opeidAssociatedToUser =
_uow.InstitutionPointOfContactRepository
.GetAllPocsByEmail(email)
.ToList();
if (opeidAssociatedToUser.Count == 0)
{
addPoc.IDNumber = "N/A";
}
else
{
string[] idArray = idAssociatedToUser
.Select(x => x.IDNumber)
.ToArray();
addPoc.IDNumber = string.Join(",", opeidArray);
}
pocs.Add(addPoc);
}
pocEmailAddresses.AddRange(pocs);
}
}
ViewBag.UploadProgress = 0;
// if any poc addresses were found...
if (pocEmailAddresses.Count > 0)
{
string emailBody = WebUtility.HtmlDecode(systemGeneralAnnouncement.EmailBody);
foreach (InstitutionPointOfContact emailAddress in pocEmailAddresses.Where(x => x.Email != "" && x.Email != null).ToList())
{
string firstName = emailAddress.FirstName == null ? "" : emailAddress.FirstName.Trim();
string lastName = emailAddress.LastName == null ? "" : emailAddress.LastName.Trim();
string userName = firstName + " " + lastName;
//iterative for progress bar
ViewBag.UploadProgress++;
}
}
return Json (ViewBag.UploadProgress, JsonRequestBehavior.AllowGet);
}
AJAX:
$
(document).ready(function(){
$.ajax({
type: "POST",
url: "progressFunction",
cache: false,
cacheControl: "no-cache",
statusCode: {
500: function () {
errorWhileSavingData()
}
},
success: function (data) {
alert()
GenerateProgressBar(data);
}
});
});
My question is, can I retrieve the individual count from the Controller (Viewbag.uploadProgress) in the post function so that I can pass it as a variable count in a progress bar?
Update: For clarity, what I need to do is get the individual count of the foreach (1 ~ n), not the completed count, which is what I am receiving now.
Update 2: SingalR is not really an option in this case, as it would be excessive for such a small process, a desired result would come from a "roll your own"
To answer your question, this isn't possible given your current setup. Nice attempt with using the ViewBag, but the ViewBag isn't actually passed between Controller and View until the Action is completed and returns to the View. As I mentioned, SignalR would be one way to approach this, but is overkill for your use case.

Foreach is not checking properly in mvc when doing a workflow

Am doing a workflow cheching in which i have 2 values and the when the foreach condition is checked only one time it enters the loop and exits out without going to the next one.
public CustomBusinessServices InvokeWorkFlowPermissionBusinessRule(dynamic workFlowImplemented, out string serviceName, out int permissionId)
{
try
{
List<WorkflowEligibilityMapping> workFlowPermissionService = new List<WorkflowEligibilityMapping>();// to handle null values
int current_ControllerId = Convert.ToInt32(workFlowImplemented); //ControllerId
using (var db = new AdminDb())
{
//to select services against this controller
workFlowPermissionService = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId)
select new WorkflowEligibilityMapping
{
Service = permission.Service,
WorkFlowPermissionId = permission.WorkFlowPermissionId
}).ToList();
}
int[] workFlowServiceDetails = workFlowPermissionService.Select(x => x.WorkFlowPermissionId).ToArray();
//to Login userId
var userId = Assyst.PanERP.Common.AppSession.Common.UserID;
/*******************Issue in foreach i think**************************************/
foreach (int workFlowServiceDetail in workFlowServiceDetails)
/*******workFlowServiceDetails have 2 valus********/
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
}
catch (Exception ex)
{
throw ex;
return null;
}
}
workFlowServiceDetails have 2 values and the workFlowServiceDetail takes the first one and checks for it.goes through the loop and mapes the role for the first one to the user list at the end and the without checking the for the second vale it moves out of the loop. Please help me to make the loop work for 2 values.Is it some problem in the return part...?
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
If any of the above if statements evaluates to true, your loop will exit without looping through the second item in your array. The reason for this is that you are in your first conditional check do the following:
return new CustomBusinessServices() { strMessage = validationMessage };
And in your second:
return userLists;
The return statement will exit your method, and therefore terminate the foreach as well.
Try building your object first, and after your loop has walked through each item, do a return statement returning your object.

Can't find a certain item in DB if it's name is duplicated

I'm going to speak about ASP.NET MVC 4 Web Application.
I have a database of users (Entity Framework). I can add, delete or search for user by his name or email, or both. It works fine if, for example, I search for "George" and there is only one George in the table. But if there are more users with these name, I need to show them all. Insted I have an exception.
Here is my controller's action for Search:
[HttpPost]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ActionResult Search(User userinfo)
{
const string noResult = "Search Result Not Found";
var itemforSearch = new User();
using (var uc = new UserContext())
{
if (userinfo.Name == null && userinfo.Email == null)
{
List<User> users;
users = uc.UserList.ToList();
return new JsonResult { Data = null };
}
if (userinfo.Name != null)
{
itemforSearch = uc.UserList.SingleOrDefault(o => o.Name == userinfo.Name);
return GetSearchedItem(noResult, itemforSearch);
}
else
{
if (userinfo.Email != null)
{
itemforSearch = uc.UserList.SingleOrDefault(o => o.Email == userinfo.Email);
return GetSearchedItem(noResult, itemforSearch);
}
}
}
return View(itemforSearch);
}
private ActionResult GetSearchedItem(string noResult, Models.User itemforSearch)
{
if (itemforSearch != null)
{
return new JsonResult { Data = itemforSearch };
}
else
{
throw new Exception("User with provided information was not find");
}
}
Here is my script that works after clicking "Search" button:
<script type="text/javascript">
function DbSearch() {
// Get some values from elements on the page:
var serchedName = $("input[name='SearchName']").val(),
searchedEmail = $("input[name='SearchEmail']").val();
var user = { Name: serchedName, Email: searchedEmail };
$.ajax(
{
type: "POST",
url: "Search",
data: JSON.stringify({ userinfo: user }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSearchSuccess,
error: OnError
});
}
function OnSearchSuccess(data) {
var tableContent = "<tr>" +
"<td>" + data.UserId + "</td>" +
"<td>" + data.Name + "</td>" +
"<td>" + data.Email + "</td>" +
"</tr>";
$('#UserTable').empty();
$("#UserTable").append(tableContent);
$("#UserTable").fnDraw();
}
function OnError(data) { }
</script>
Actually, I think the problem is in my LINQ expression, when I use SingleOrDefault (I got {System.InvalidOperationException} but how can i fix it?
When using SingleOrDefault you will get an exception when the dataset has multiple rows that match your condition, This property is also explained in the documentation http://msdn.microsoft.com/en-us/library/vstudio/bb342451.aspx
If you want to return a list of users that match your request you should use the .where() method.
Like so: itemforSearch = uc.UserList.Where(o => o.Name == userinfo.Name).ToList();
Or if you just want a single matching row you can use .firstOrDefault().
Like this: itemforSearch = uc.UserList.FirstOrDefault(o => o.Name == userinfo.Name);
EDIT further explanation on returning multiple user result
The controller and the GetSearchedItem function would need to use List<User>() to return multiple users as result, and in the view, the function OnSearchSuccess(data) would need to loop through the list of users.
Below I have modified the controller to use List but I'm not sure how to use JsonResult with a list so you would have to look that up if it doesn't work.
[HttpPost]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ActionResult Search(User userinfo)
{
const string noResult = "Search Result Not Found";
var itemforSearch = new List<User>();
using (var uc = new UserContext())
{
if (userinfo.Name == null && userinfo.Email == null)
{
List<User> users;
users = uc.UserList.ToList();
return new JsonResult { Data = null };
}
if (userinfo.Name != null)
{
itemforSearch = uc.UserList.Where(o => o.Name == userinfo.Name).ToList();
return GetSearchedItem(noResult, itemforSearch);
}
else
{
if (userinfo.Email != null)
{
itemforSearch = uc.UserList.Where(o => o.Email == userinfo.Email).ToList();
return GetSearchedItem(noResult, itemforSearch);
}
}
}
return View(itemforSearch);
}
private ActionResult GetSearchedItem(string noResult, List<Models.User> itemforSearch)
{
if (itemforSearch.Count > 0)
{
// Not sure how JsonResult works with lists but try take a look at this post http://stackoverflow.com/questions/9110724/serializing-a-list-to-json
return new JsonResult { Data = itemforSearch };
}
else
{
throw new Exception("User with provided information was not find");
}
}

Categories

Resources