I found the following code example (from Telerik ) that I'm trying to understand.
What I need to do is somehow to set static text into JsonResult (e.g.Text ="Abc" and Value="123")
public ActionResult _AjaxLoading(string text)
{
Thread.Sleep(1000);
using ( var nw = new NorthwindDataContext() )
{
var products = nw.Products.AsQueryable();
if ( text.HasValue() )
{
products = products.Where((p) => p.ProductName.StartsWith(text));
}
return new JsonResult { Data = new SelectList(products.ToList(), "ProductID", "ProductName") };
}
}
public ActionResult _AjaxLoading(string text
{
var data = new { Text= "123", Value= "Abc"};
return Json(data, JsonRequestBehavior.AllowGet);
}
If it is an HTTPGet method, You should specify JsonRequestBehavior.AllowGet as second parameter to return JSon data from a GET method
It looks like you are in need of this:
return new JsonResult { Data = new { Text="Abc", Value="123", Produtcs= new SelectList(products.ToList(), "ProductID", "ProductName") }};
Is this what you are looking for
return new JsonResult { Text = "Abc", Value="123" };
If you want to add a new element to the drop down at start then
var editedProducts = new SelectList(products.ToList(), "ProductID","ProductName" ).ToList();
editedProducts.insert(0, new SelectListItem() { Value = "123", Text = "Abc" });
return new JsonResult { Data = editedProducts };
Related
I have string value like below example for fax
string fax="1111111111";
I need below result for above string to add special character for fax format like below.
(111)-111-1111
my code for reference because my question going down please help any to get result
var list = (dynamic)null;
if (!String.IsNullOrEmpty(faxdos.medicalRecordsFax) && !String.IsNullOrEmpty(faxdos.fax))
{
list = new List<SelectListItem>
{
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.medicalRecordsFax)+" - Medical Records Fax", Value = faxdos.medicalRecordsFax},
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.fax), Value = faxdos.fax },
};
}
else if (!String.IsNullOrEmpty(faxdos.medicalRecordsFax))
{
list = new List<SelectListItem>
{
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.medicalRecordsFax)+" - Medical Records Fax", Value = faxdos.medicalRecordsFax},
};
}
else if (!String.IsNullOrEmpty(faxdos.fax))
{
list = new List<SelectListItem>
{
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.fax), Value = faxdos.fax },
};
}
else
{
list = new List<SelectListItem>
{
new SelectListItem{ Text="", Value = "" },
};
}
// ViewBag.emp = list;
var result = new SelectList(list, "Text", "Value");
return Json(result, JsonRequestBehavior.AllowGet);
well how about just writing code to do it
string fax="1111111111";
string str2 = $"({fax.Substring(0,3)})-{fax.SubString(3,3)}-{fax.Substring(6,4)}";
If you want to use the var result = string.Format("{0:(###)-###-####}", someValue) formatting mechanism, then the value you are formatting needs to be a number, not a string. So you could do something like this:
var telNoString = "1111111111";
if (long.TryParse(telNoString, out var telno))
{
var result = string.Format("{0:(###)-###-####}", telno);
Debug.WriteLine(result);
}
Which will result in (111)-111-1111 in the debug console.
So I have put together a group of stored procedure calls in my web api controller. Now I need to return the combined results. Javascript is as simple as something like this:
var result = [{
objectResult: value
},{
arryResult1:[value]
},{
arryResult2:[value]
}]
but it c# it would require a class that contains 2 lists and a object? then return that as a list? this is where i am kind of lost.
[HttpPost]
[Route("builderContact")]
public List<usp_get_builder_contact_data_Result> GetBuilderContact(parameter parameter)
{
object[] parameters = { parameter.company_id, parameter.subdivision_id };
var builderContact = db.Database.SqlQuery<usp_get_builder_contact_data_Result>("sandbox.usp_get_builder_contact_data {0},{1}",
parameters).First();
var floorplanDataResult = db.Database.SqlQuery<usp_get_floorplan_data_Result>("sandbox.usp_get_floorplan_data {0},{1}",
parameters).ToList();
var floorplanRelatedResult = db.Database.SqlQuery<usp_get_floorplan_related_sections_Result>("sandbox.usp_get_floorplan_related_sections {0},{1}",
parameters).ToList();
return ?;
}
update for answer
[HttpPost]
[Route("bigEnchilada")]
public List<object> GetBuilderContact(parameter parameter)
{
object[] parameters = { parameter.company_id, parameter.subdivision_id };
var builderContact = db.Database.SqlQuery<usp_get_builder_contact_data_Result>("sandbox.usp_get_builder_contact_data {0},{1}",
parameters).First();
var floorplanDataResult = db.Database.SqlQuery<usp_get_floorplan_data_Result>("sandbox.usp_get_floorplan_data {0},{1}",
parameters).ToList();
var floorplanRelatedResult = db.Database.SqlQuery<usp_get_floorplan_related_sections_Result>("sandbox.usp_get_floorplan_related_sections {0},{1}",
parameters).ToList();
return (new object[] {
new object { builderContact = builderContact },
new object { floorplanDataResult = floorplanDataResult },
new object { floorplanRelatedResult = floorplanRelatedResult }
}).ToList();
}
If you want it to match exactly what you have in Javascript, then change the return type to List<object> and return:
return new List<object> {
new { objectResult = builderContact },
new { arryResult1 = floorplanDataResult },
new { arryResult2 = floorplanRelatedResult }
};
IMHO in this context the following model would be much more suited (if you can change it, that is):
var result = {
objectResult: value,
arryResult1: [value],
arryResult2: [value]
}
In which case you would set the return type to object and return:
return new {
objectResult = builderContact,
arryResult1 = floorplanDataResult,
arryResult2 = floorplanRelatedResult
};
A tiny bit nicer, no?
You can simply concat them all ?
List<object> allItems = (
from x in floorplanDataResult.ToList() select new object()
).ToList().Concat(
from y in floorplanRelatedResult.ToList() select new object()
).ToList();
return allItems;
I don't know if your client expects them in the same payload though...
might seem really simple however I can't get my json to be correctly formatted from my MVC 5 controller.
My output is showing as;
[
{
"result":{
"account_color":"B43104",
"account_desc":"Welcome to XYZ",
"account_name":"XYZ",
"account_zone":1
}
},
{
"result":{
"account_color":"FF0000",
"account_desc":"Test Company",
"account_name":"Test",
"account_zone":2
}
}
]
So as you can see the level above result does not show any text so it seems like the 'result' section is getting added to a blank node
My controller is;
public IEnumerable<dynamic> Get()
{
return db.tblAccounts.Select(o => new
{
result = new
{
account_name = o.account_name,
account_desc = o.account_desc,
// account_image = Url.Content("~/images/") + String.Format("account_{0}.png", o.id),
account_color = o.account_color,
}
});
}
My json formatter is;
config.Formatters.Clear();
//config.Formatters.Add(new XmlMediaTypeFormatter());
var json = new JsonMediaTypeFormatter();
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
config.Formatters.Add(json);
so it just appears that the 'result' is at a sub level it needs to be a level higher, any help would be great.
Try changing your code to look like this:
public IEnumerable<dynamic> Get()
{
return db.tblAccounts.Select(o =>
new
{
account_name = o.account_name,
account_desc = o.account_desc,
// account_image = Url.Content("~/images/") + String.Format("account_{0}.png", o.id),
account_color = o.account_color,
}
);
}
This will produce an array of results instead of the nested JSON that you provided. you don't actually need the result node label do you?
EDIT:
based on your response is this what you are looking for?
public dynamic Get()
{
var accountsNode = new {
accounts = db.tblAccounts.Select(o =>
new
{
account_name = o.account_name,
account_desc = o.account_desc,
// account_image = Url.Content("~/images/") + String.Format("account_{0}.png", o.id),
account_color = o.account_color,
}
).ToList()
};
return accountsNode;
}
So I have a controller that returns json to my views that I need to test. I have tried using reflection with a dynamic data type to access a sub property of a list but I keep getting something similar to 'unable to cast' errors. Basically I have a list within a list that I want to access and verify things about but I can't access it. Has anyone tested json returned from their controller before in MVC4 and have advice?
Code:
// arrange
var repositoryMock = new Mock<IEdwConsoleRepository>();
var date = -1;
var fromDate = DateTime.Today.AddDays(date);
EtlTableHistory[] tableHistories =
{
new EtlTableHistory
{
Table = new Table(),
RelatedStatus = new BatchStatus(),
BatchId = 1
}
};
EtlBatchHistory[] batchHistories = { new EtlBatchHistory
{
Status = new BatchStatus(),
TableHistories = tableHistories
} };
repositoryMock.Setup(repository => repository.GetBatchHistories(fromDate)).Returns((IEnumerable<EtlBatchHistory>)batchHistories);
var controller = new EdwController(new Mock<IEdwSecurityService>().Object, repositoryMock.Object);
// act
ActionResult result = controller.BatchHistories(1);
// assert
Assert.IsInstanceOfType(result, typeof(JsonResult), "Result type was incorrect");
var jsonResult = (JsonResult)result;
var resultData = (dynamic)jsonResult.Data;
var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);
var returnedTableHistoriesType = returnedHistories.GetType();
Assert.AreEqual(1, returnedTableHistoriesType.GetProperty("Count").GetValue(returnedHistories, null), "Wrong number of logs in result data");
Here's an example:
Controller:
[HttpPost]
public JsonResult AddNewImage(string buildingID, string desc)
{
ReturnArgs r = new ReturnArgs();
if (Request.Files.Count == 0)
{
r.Status = 102;
r.Message = "Oops! That image did not seem to make it!";
return Json(r);
}
if (!repo.BuildingExists(buildingID))
{
r.Status = 101;
r.Message = "Oops! That building can't be found!";
return Json(r);
}
SaveImages(buildingID, desc);
r.Status = 200;
r.Message = repo.GetBuildingByID(buildingID).images.Last().ImageID;
return Json(r);
}
public class ReturnArgs
{
public int Status { get; set; }
public string Message { get; set; }
}
Test:
[TestMethod]
public void AddNewImage_Returns_Error_On_No_File()
{
// Arrange
ExtendedBuilding bld = repo.GetBuildings()[0];
string ID = bld.Id;
var fakeContext = new Mock<HttpContextBase>();
var fakeRequest = new Mock<HttpRequestBase>();
fakeContext.Setup(cont => cont.Request).Returns(fakeRequest.Object);
fakeRequest.Setup(req => req.Files.Count).Returns(0);
BuildingController noFileController = new BuildingController(repo);
noFileController.ControllerContext = new ControllerContext(fakeContext.Object, new System.Web.Routing.RouteData(), noFileController);
// Act
var result = noFileController.AddNewImage(ID, "empty");
ReturnArgs data = (ReturnArgs)(result as JsonResult).Data;
// Assert
Assert.IsTrue(data.Status == 102);
}
In your example it looks to me that the problem is here:
var resultData = (dynamic)jsonResult.Data;
var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);
The resultData object would be the exact type of the object that you returned in your action. So if you did something like:
List<String> list = repo.GetList();
return Json(list);
Then your resultData would be of type:
List<String>
Try making sure that you are returning your Object using the Json(obj) function.
You can deserialize your Json into a dynamic object and then ask for the property you want
Example:
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var propertyValue = obj.MyProperty; //Ask for the right property
You can add Json serializer from Nuget Json.Net package.
I have a problem in my asp.net mvc4 application :
i'am passing two integers as a parameteres to an action :
<a>#Html.ActionLink(s, "Gerer_Sequence", "Travail", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire } )</a>
the action is :
public ActionResult Gerer_Sequence(int seq, int affa)
{
Session["affaire"] = affa;
Session["sequence"] = seq;
return RedirectToAction("Index", "Calendar");
}
the problem is that the parameters are null however the its values are 3 and 1 in the model.
So what is the problem? How can i modify my code to fix the error?
Try this.
<td>
#Html.ActionLink("EditUser", "Index", new { Id = m.ID,Name = m.Name })
</td>
public ActionResult Index(string Id, string Name)
{
var model = new RegisterModel();
int _ID = 0;
int.TryParse(Id, out _ID);
if (_ID > 0)
{
RegisterModel register = GetRegisterUserById(_ID);
model.ID = _ID;
model.Name = register.Name;
model.Address = register.Address;
model.PhoneNo = register.PhoneNo;
}
return View(model);
}
You just need to change this:
new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire }
to this:
new RouteValueDictionary { { "seq", Model[k][i].Id_séquence }, { "affa", aff.Id_affaire } }
because the fourth parameter you're using is the route values.
Try this:
#Html.ActionLink(s, "Gerer_Sequence", "Travail", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire }, null )
Remove the tag
Ensure that parameters you have provided are int values.
After that run your application and check the link generated, if values are ok then it should be ok.
i put the action in the same controller:
#Html.ActionLink("Gerer Sequence", "Gerer_Sequence", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire } )