I am not understand this case:
I have a model like:
public class ExmDescobertos {
public int Id { get; set; }
public int ExameId { get; set; }
public int PlanoId { get; set; }
public int ConvenioId { get; set; }
}
And create an object javascript:
var objDescoberto = new Object();
objDescoberto.Id = $("#hdnDescobertoId").val(); //inputs with values...
objDescoberto.ExameId = $('#hdnExameId').val();
objDescoberto.PlanoId = $('#hdnPlanoId').val();
objDescoberto.ConvenioId = $('#hdnConvenioId').val();
And I am using Json.stringify(obj) to transmit the values with a $.post jQuery method:
var dados = JSON.stringify(objDescoberto);
In this point, dados is "{"Id":"27","ExameId":"53","PlanoId":"32","ConvenioId":"11"}", for example.
And have a controller with this action:
public PartialViewResult(ExmDescobertos descoberto) { }
But... the parameter in this controller not receive your values correct! :o
In this point descoberto is Id = 0; ExameId = 0; PlanoId = 0; ConvenioId = 0;
Not errors explicit, but not works...
Anybody have a idea of what I have missing?
Thank you for all!
Don't stringify you object, just send object as is.
$.post("/url", objDescoberto);
or
var dados = JSON.stringify({descoberto : objDescoberto});
Related
This is my javascript to load partial view by sending a data array as a parameter.
$('body').on('click', '.btn-add-answer', function () {
var answerObj = Array.from(GetAnswerDetails(this));
var lastAnswer = answerObj[answerObj.length - 1];
var answers = {};
answers.Id = parseInt(lastAnswer.Id) + 1;
answers.FormQuestionId = lastAnswer.FormQuestionId;
answers.Text = "";
answers.IsCorrect = false;
answers.Score = null;
answers.QuestionAnswerId = 0;
answers.Sequence = 0;
answerObj.push(answers);
$("#survey-answer-container")
.load("LoadTest", answerObj);
});
This is my controller
public ActionResult LoadTest(List<AnswerDto> answers)
{
return PartialView("_SurveyPageSectionQuestionAnswer", answers);
}
And this is my DTO
public class AnswerDto
{
public int Id { get; set; }
public string Text { get; set; }
public int Sequence { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public int FormQuestionId { get; set; }
public int QuestionAnswerId { get; set; }
}
The issue is the parameter didn't get to the controller. The 'answers' parameter in the controller will only have default values.
How to send data array from javascript as a parameter in partial view load?
Try your object like below. Wrap your object as { answers: answerObj } so it could match with parameter name.
$("#survey-answer-container")
.load("LoadTest", { answers: answerObj });
There's a javascript library called Crypto-js and i'm trying to convert some methods I use to c#.
For example in javascript:
var payload = JSON.stringify({ market: "BTC-ETH", order: { price: "0.02159338", side: "buy", size: "0.024" } });
var contentHash = cryptoJS.SHA512(payload).toString(cryptoJS.enc.Hex);
console.log(contentHash);
In C#
public class OrdersVM
{
public string Market { get; set; }
public Order Order { get; set; }
}
public class Order
{
public string Price { get; set; }
public string Side { get; set; }
public string Size { get; set; }
}
public async Task<IActionResult> Orders([FromBody] OrdersVM vm) {
var payload = JsonConvert.SerializeObject(vm);
var contentHash = sha512Hex(payload).ToLower();
Console.WriteLine(contentHash);
}
public string sha512Hex(string input)
{
var bytes = Encoding.UTF8.GetBytes(input);
using (var hash = SHA512.Create())
{
hash.ComputeHash(bytes);
return BitConverter.ToString(hash.Hash).Replace("-", "");
}
}
contentHash for javascript is
"99bb05af8aace509189e08625bb4e475a9daaafc92edf5c85fa1aefcc16c16e4533c23843c5806aef01c97e8cb4150b2dc129d04d3b6a50331833fe5cb8158fc"
and for c#
"731b92cf482ff90ffe759e356959ec005334062bdc3c2cc78b48c3041d21a45ecaa6b33f6df2971fa868f94f04b7596e818104cb1017ed1c436365beac3a01d1"
What am I doing wrong with c# conversion?
The issue is that JSON.Net, by default, will serialise your property names exactly as the appear, meaning they all start with a capital letter. There are two ways to fix this:
Using JsonProperty to explicitly control the property name serialisation. For example:
public class OrdersVM
{
[JsonProperty("market")]
public string Market { get; set; }
[JsonProperty("order")]
public Order Order { get; set; }
}
Use a contract resolver to tell JSON.Net how to process the names. Fortunately there is one provided for you that will do this:
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
var payload = JsonConvert.SerializeObject(vm, settings);
I am building a scheduling system using fullcalendar for MVC, my get event retrieves from a view for a specific location.
However, my post / save event inserts into the table that the view is made from, containing all locations.
I am getting an error when I try to add the new event to the data connection.
"The field Location must be a string or array type with a maximum length of '1'." string
PropertyName "Location" string
I tried to set the string for the event manually before adding it to the data connection but this isn't working for some reason. Could it be me not declaring the string correctly?
//Actions for Calendar 5
public JsonResult GetEvents5()
{
using (CalgaryNEEntities dc = new CalgaryNEEntities())
{
var events = dc.CalgaryNEEvents.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent5(EventsAllLocation e)
{
var status = false;
using (InsertEntities dc = new InsertEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.EventsAllLocations.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
var locationstring = "Calgary NE Kitchens";
v.CompanyName = e.CompanyName;
v.Start = e.Start;
v.End = e.End;
v.KitchenNumber = e.KitchenNumber;
v.Location = locationstring;
}
}
else
{
var locationstring = "Calgary NE Kitchens";
e.Location = locationstring;
dc.EventsAllLocations.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
Here is the EventsAllLocation definition:
public partial class EventsAllLocation
{
public int EventID { get; set; }
public string Location { get; set; }
public string CompanyName { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string KitchenNumber { get; set; }
}
Any tips or help would be greatly appreciated, thanks!
The answer is staring you in the face !! LOL
"The field Location must be a string or array type with a maximum
length of '1'." string PropertyName "Location" string
I have an api controller and a viewmodel as given below that fetch a set of records from an sql db and pass it to a razor view into a kendo grid.
Viewmodel:
public class SoonDueReportsViewModel
{
public SoonDueReportsViewModel()
{
}
public string ARAName { get; set; }
public int? ReportAraId { get; set; }
public string CompanyName { get; set; }
public int? CompanyId { get; set; }
public string ReportDetails { get; set; }
public DateTime? DueReportDate { get; set; }
public int ReportId { get; set; }
}
Controller:
public class AllDueReportsController : BaseApiController
{
private readonly IIdentityStorage identityStorage;
public IQueryable<SoonDueReportsViewModel> Get()
{
AppKatPrincipal appKatPrincipal = identityStorage.GetPrincipal();
var araIds = UnitOfWork.GetAll<UserGroup>()
.Where(group => group.Id == appKatPrincipal.GroupId)
.SelectMany(group => group.ARA).Select(ara => ara.Id);
var duties = UnitOfWork.GetAll<Duty>();
var companies = UnitOfWork.GetAll<Company>();
var aras = UnitOfWork.GetAll<ARA>().Where(x => araIds.Contains(x.Id));
var userGroupId = indireKatPrincipal.GroupId;
var userGroup = UnitOfWork.GetById<UserGroup>(userGroupId);
var foreRun = userGroup.ForRun.GetValueOrDefault();
var nextDate = DateTime.Today.AddMonths(foreRun); // The value of this variable I need to transport also to the view !!
var query = from ara in aras
join company in companies on ara.Id equals company.ARA
join duty in duties on company.Id equals duty.CompanyId
where duty.ReportedDate == null
&& company.Activ == true
select new SoonDueReportsViewModel
{
ARAName = ara.Name,
ReportAraId = ara.Id,
CompanyName = company.Name,
CompanyId = company.ID,
ReportDetails = duty.Details,
DueReportDate = duty.ReportDate,
ReportId = duty.Id,
};
return query;
}
}
Everything works fine, but in addition to the set of records (defined by the query) I also need to transport the value of the variable 'nextDate' to the same view.
If someone could give me a hint how to do this, I'd appreciate it a lot.
Regards, Manu
Server returns the array of object in JSON. It looks so:
{"d":"[
{\"Id\":1,\"IsGood\":true,\"name1\":\"name1dsres\",\"Name2\":\"name2fdsfd\",\"name3\": \"name3fdsgfd\",\"wasBorn\":\"\\/Date(284011000000)\\/\"},
{\"Id\":2,\"IsGood\":false,\"name1\":\"fdsfds\",\"name2\":\"gfd3im543\",\"name3\":\"3543gfdgfd\",\"WasBorned\":\"\\/Date(281486800000)\\/\"}
]"}
I need to parse using JSON.parse function. I'm doing this this way:
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON.d) {
// how do I get the fields of current item?
}
This code is not working, it returns undefined
for (var item in parsedJSON) {
alert(item.Id);
}
This works perfectly
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var i=0;i<parsedJSON.length;i++) {
alert(parsedJSON[i].Id);
}
}
But this doens't
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON) {
alert(item.Id);
}
}
You can just access them as you would any object:
var id = item.Id;
if (item.IsGood) { ... }
If you wish to enumerate them to use somehow, have a look at this SO question.
You can access them as you do oridinary javascript objects,
that is either as item.id or item['id']
class Program
{
static void Main(string[] args)
{
var jsonString = #"{
""data"": [
{
""uid"": ""100001648098091"",
""first_name"": ""Payal"",
""last_name"": ""Sinha"",
""sex"": ""female"",
""pic_big_with_logo"": ""https://m.ak.fbcdn.net/external.ak/safe_image.php?d=AQAi8VLrTMB-UUEs&bust=1&url=https%3A%2F%2Fscontent-a.xx.fbcdn.net%2Fhprofile-ash2%2Fv%2Ft1.0-1%2Fs200x200%2F10018_433988026666130_85247169_n.jpg%3Foh%3Dc2774db94dff4dc9f393070c9715ef65%26oe%3D552CF366&logo&v=5&w=200&h=150"",
""username"": ""payal.sinha.505"",
},
]
}";
dynamic userinfo = JValue.Parse(jsonString);
IList<FacebookUserDetail> userDeatils = new List<FacebookUserDetail>();
// 1st method
foreach (dynamic userinfoItr in userinfo.data)
{
FacebookUserDetail userdetail= userinfoItr.ToObject<FacebookUserDetail>();
userDeatils.Add(userdetail);
}
// 2nd Method
var userDeatils1 = JsonConvert.DeserializeObject<FacebookUserDetails>(jsonString);
}
}
public class FacebookUserDetail
{
public string username { get; set; }
//Password = EncryptionClass.Md5Hash(Guid.NewGuid().ToString()),
public string first_name { get; set; }
public string last_name { get; set; }
public string sex { get; set; }
public string pic_big_with_log { get; set; }
}
enter code here
public class FacebookUserDetails
{
public IList<FacebookUserDetail> data { get; set; }
}
}