I have the following method which is supposed to return a JSONResult so I can use it in an AJAX method with javascript and load autocomplete suggestions for a textbox. I will load this everytime a particular dropdown list changes.
[AcceptVerbs(HttpVerbs.Post), Authorize]
private JsonResult GetSchemaNodeValues(string SchemaNodeId)
{
var query = #"Select ld.""Value""
From ""LookupData"" ld, ""SchemaNode"" sn
Where sn.""LookupTypeId"" = ld.""LookupTypeId""
And sn.""SchemaNodeId"" = '{0}'";
DataSet data = new DataSet();
data = ServiceManager.GenericService.ExecuteQuery(String.Format(query, SchemaNodeId)).Data;
var res = data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
return JsonConvert.SerializeObject(res);
}
I get the following error under return JsonConvert.SerializeObject(res);
Error 106 Cannot implicitly convert type 'string' to 'System.Web.Mvc.JsonResult'
Is there any way to get past this?
Before this I tried using System.Web.mvc.Controller.Json(res); which returns a JSONResult from an object.
But I couldn't use it because my class is a PageDialog not a Controller so it doesn't have access to Controller's protected internal methods like JSon(). The error I got was that JSon() is inaccessible due to its protection level. The Controller class was locked and I can't make it public or create a workaround so I changed the approach using JsonConvert.SerializeObject(res);
Any suggestions would be extremely welcome.
private dynamic GetSchemaNodeValues(string SchemaNodeId)
{
...
return data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
}
or
private string GetSchemaNodeValues(string SchemaNodeId)
{
...
var result = data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
return JsonConvert.SerializeObject(result);
}
Related
This passes
var badRequestObjectResult = new BadRequestObjectResult(new { ErrorMessage = "Hi" });
dynamic response = badRequestObjectResult.Value;
Assert.Equal("Hi", response.ErrorMessage);
While this fails
dynamic response2 = ((BadRequestObjectResult)result).Value;//result is an IActionResult
Assert.Equal("Hi", response2.ErrorMessage);
"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'object' does not contain a definition for 'ErrorMessage'"
You will need to extend your answer to include a complete and reproducible example. What you describe works as expected without an error so there must be something in-between that is causing an issue such as custom cloning or serialization that is altering the recognized type behind the ObjectResult's Value.
[Test]
public void TestDynamic()
{
var response1 = new BadRequestObjectResult(new { Message = "Hi." });
var response2 = buildResponse();
dynamic value1 = response1.Value;
dynamic value2 = ((BadRequestObjectResult)response2).Value;
string message1 = value1.Message;
string message2 = value2.Message;
Assert.AreEqual(message1, message2);
}
private IActionResult buildResponse()
{
return new BadRequestObjectResult(new { Message = "Hi." });
}
About the only way I could reproduce the error was if buildResponse returned:
return new BadRequestObjectResult(new object());
Returning anything like an anonymous type or another class that lacked a Message property resulted in a message that reflected the underlying type.
I have a method like this:
[HttpPost]
[ActionName("GetUserData")]
public ActionResult GetUserData()
{
using (var ctx = new myEntities())
{
ctx.Configuration.LazyLoadingEnabled = false;
ctx.Configuration.ProxyCreationEnabled = false;
var user = ctx.Users.Include("UserRoles").FirstOrDefault(x => x.UserId == 4);
ctx.Configuration.LazyLoadingEnabled = true;
ctx.Configuration.ProxyCreationEnabled = true;
return Json(new
{
Email = user.Email,
Roles = user.UserRoles
}, JsonRequestBehavior.AllowGet);
}
}
The post is done via jQuery like this:
$.post("/Administrator/GetUserData", function (data) {
console.log(data);
});
I'm trying to write out the returned data, but the console is showing me Internal Error 500 when I write the code like above...
In other case when returned result is like this:
return Json(new
{
Email = user.Email
// returning just email for example to see in console..
},JsonRequestBehavior.AllowGet);
Returning just email as a plain simple string works okay, but when I try to return the User's roles as an array via JSON , then I get problems like above...
The collection UserRoles is of Type ICollection...
What am I doing wrong here?
P.S. Guys I dug out the exception, it's like following:
Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Collections.Generic.HashSet`1[[MyModel.Models.DatabaseConnection.UserRoles, MyEntity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
it’s clear that your model of role contains a property point to user which causes the issue.
you should select an anonymous object to return
Roles = user.Roles.Select(r=> new { name = r.Name }).ToArray();
I am using Entity Framework to get db data. I wrote an action to return table data in JSON format as below:
public JsonResult GetEmployeesData()
{
using (TrainingDBEntities db = new TrainingDBEntities())
{
return new JsonResult { Data = db.Employees, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
It's not throwing any exception. But a console error is occurring with error code: 500. When I debugged, it showed an error
The function evaluation requires all threads to run
When I try to reload, a new error occurs:
Unable to evaluate the expression. Operation not supported. Unknown error: 0x80070057
I don't have any idea what's wrong with this code?
The solution is :
public JsonResult GetEmployeesData()
{
using (TrainingDBEntities db = new TrainingDBEntities())
{
var emps = db.Employees.ToList();
return new JsonResult { Data = emps, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
I think accessing db inside the JsonResult{} is causing the issue.
Evaluation is working properly because you have not converted result set into a valid datatype for JSON.
You can replace below code
JsonResult { Data = db.Employees, JsonRequestBehavior = ..}
with
JsonResult { Data = db.Employees.ToList(), JsonRequestBehavior = ..}
I'm trying to insert some data inside my database but I get an error on my HttpPost
here it is :
[HttpPost]
public ActionResult Registration(UserInformationViewModel info)
{
var client = new MongoClient("mongodb://localhost:27017");
var objDatabase = client.GetDatabase("Test");
var collection = objDatabase.GetCollection<BsonDocument>("Users");
collection.InsertOne<UserInformationViewModel>(info);
return View("_ModalContent");
}
So i get this error
The non-generic method
'IMongoCollection.InsertOne(BsonDocument,
InsertOneOptions, CancellationToken)' cannot be used with type
arguments MVCWithMongo C:\Quentin\Repos\Test\MVCWithMongo\MVCWithMongo\Controllers\UserController.cs 34 Active
I can't figure out why.
If someone could help, would be nice!
I made a modification, i don't have the error anymore but nothing happens.
[HttpPost]
public ActionResult Registration(UserInformationViewModel info)
{
var client = new MongoClient("mongodb://localhost:27017");
var objDatabase = client.GetDatabase("Test");
var collection = objDatabase.GetCollection<UserInformationViewModel>("Users");
collection.InsertOne(info);
return View("_ModalContent");
}
I am having a login method. Within this method i am checking for any invalid data being picked from repository(i.e. i am calling a more function to check invalid data). Before adding the invalid check method the login method was returning return RedirectToAction("HomePage", "Home"); but now i am unable to figure out that how to redirect the user to another view within this login method. Below is the code that i have written -
List<InvalidModel> invalidModel = new List<InvalidModel>();
List<object> invalidModelList = new List<object>();
var jsonData = new { rows = new List<object>() };
invalidModel = GetInvalidItems();
if (invalidModel.Count > 0)
{
foreach(var invld in invalidModel)
{
invalidModelList.Add(new
{
cell = new string[]
{
invld.InvalidItemID,
invld.InvalidItemName,
}
});
}
}
jsonData = new { rows = invalidModelList};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Now i am confused that how to send this json data to a view that will show all invalid items in grid?
Please help.
how about something like this?
if(invalidModelList.count > 0)
return View("view_with_grid",invalidModelList);
else
return RedirectToAction("HomePage", "Home");