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));
}
Related
I'm building a project with asp.net.
Part of the the project is a view (using google maps api) that is showing the the status of the parking lots with maerkers on the map.
Im using JSON file to create the markers.
Moreover, Im using arduino with some sensors that are indicated of the parking lot status.
I want that this Json will be update (override the previous) every 2 seconds (so that if a car enters the parking lot and now its full - it will present on the map as full)
I have 2 functions that creates this Json's and I want to call them every 2 seconds as I said before.
I could not do it. I'll be glad to receive your help.
The name of the view page: "TotalPs".
This is the controller in which the relevant function is located:
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
return View();
}
public ActionResult TotalPData()
{
ReadArduino(); //READ THE DATA FROM THE ARDUINO
callA(); // CREATES THE FIRST JSON
callB(); // CREATES THE 2ND JSON
var totalQueryParkingLot =
from lot in db.parkingLots
orderby lot.PricePerHour
select lot;
return Json(totalQueryParkingLot);
}
public void callA()
{
var totalQueryParkingLot =
from lot in db.parkingLots
orderby lot.PricePerHour
select lot;
var data2 = totalQueryParkingLot.ToList();
var jsonString2 = JsonConvert.SerializeObject(data2);
if (jsonString2 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJsonPL.json"), jsonString2);
}
public void callB()
{
var FreeQueryParkingLot =
from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select pub;
var data8 = FreeQueryParkingLot.ToList();
var jsonString3 = JsonConvert.SerializeObject(data8);
if (jsonString3 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJsonPU.json"), jsonString3);
}
public void ReadArduino()
{
SerialPort port = new SerialPort("COM3", 9600);
port.BaudRate = 9600;
port.PortName = "COM3";
port.Open();
bool status1 = true;
bool status2 = true;
bool status3 = true;
char[] arr = new char[4];
String data_arduino = port.ReadLine();
for (int i = 0; i < arr.Length; i++)
{
char first = data_arduino[i];
arr[i] = first;
}
int space = arr[0] - 48;
var arduinoQuery1 = from b in db.parkingLots where b.parkingLotID == 22 select b;
foreach (parkingLot parkingLot in arduinoQuery1)
{
parkingLot.freeSpaces = space;
}
db.SaveChanges();
}
In the view I call the function TotalPData() that is calling to the other functions.
Tnx!!
I am assuming that you are applying a ajax call to retrieve json data. So, you can assign interval using setInterval to execute ajax call periodically.
var interval = setInterval(ajaxCall, 5000); //5000 MS == 5 seconds
function ajaxCall() {
clearInterval(interval);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'Controller/TotalPData',
dataType: "json",
success: function (response) {
interval = setInterval(ajaxCall, 5000);
// Do something
},
error: function (a, b, c) {
}
});
}
Also, It could be better to use SignalR to perform this kind of requirements.
SignalR
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");
}
}
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.
I'm using javascript to set the value of a cookie when I open the debugger panel so that if the user has already opened it, it will automatically open when they reload the page.
Here is the javascript:
jQuery(document).ready(function () {
DebuggingPanel.init(jQuery);
DebuggingPanel.GetPanelState();
});
DebuggingPanel.GetPanelState = function () {
jQuery.ajax({
url: "/sitecore modules/DebuggingPanel/DebuggingPanel.asmx/GetPanelState",
type: 'POST',
success: function(data) {
if (data.open === true) {
DebuggingPanel.TogglePanel();
}
}
});
}
DebuggingPanel.TogglePanel = function (changeState) {
var tinyDiv = $('.debuggingPanel.tinyDiv');
if (tinyDiv.text() == '+') {
tinyDiv.text('-');
DebuggingPanel.GetInformation();
DebuggingPanel.panel.slideDown();
interval = setInterval(DebuggingPanel.GetInformation, 5000);
if (changeState) {
DebuggingPanel.SetPanelState("open");
}
} else {
tinyDiv.text('+');
DebuggingPanel.panel.slideUp();
clearInterval(interval);
if (changeState) {
DebuggingPanel.SetPanelState("closed");
}
}
};
tinyDiv.click(function () {
DebuggingPanel.TogglePanel(true);
});
And here are the methods related to the cookie:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
In debugging the cookie looks as though it is getting the value correctly, but the next time I go into GetPanelState(), panelCookie.Value is always "" (not "open" as it should be, or "closed", which would indicate it was set by the toggle).
This happens when I reload the page, and it also happens when I call GetPanelState() at the end of SetPanelState(); panelCookie.Value = "open" in SetPanelState() but then equals "" in GetPanelState()
When you are reading from the Cookie, you need to use the Request instead of the response. So your code will be as follows:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
//It is here that you are reading the cookie.
var panelCookie = HttpContext.Current.Request.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
Thanks
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");
}
}