I just converted json to c# class using json2csharp.com. Then trying to pass that json from view to my controller but problem is only "create_time" object value is garbing successfully no any other value is able to grab. Also please check my debug picture to get better idea. What mistake it can be?
Json i am passing from view:
{"id":"WH-0G571461Y8752214W-8RU19841BY148894W","create_time":"2017-02-27T23:14:14Z","resource_type":"invoices","event_type":"INVOICING.INVOICE.CREATED","summary":"An invoice has been created","resource":{"id":"INV2-3RK5-HZV6-35UP-3LLU","number":"8035","template_id":"TEMP-6MT19746YC041742U","status":"DRAFT","merchant_info":{"email":"ppaas_default#paypal.com","first_name":"Dennis","last_name":"Doctor","business_name":"Medical Professionals, LLC","phone":{"country_code":"001","national_number":"5032141716"},"address":{"line1":"1234 Main St.","city":"Portland","state":"OR","postal_code":"97217","country_code":"US"}},"billing_info":[{"email":"example#example.com"}],"shipping_info":{"first_name":"Sally","last_name":"Patient","business_name":"Not applicable","phone":{"country_code":"001","national_number":"5039871234"},"address":{"line1":"1234 Broad St.","city":"Portland","state":"OR","postal_code":"97216","country_code":"US"}},"items":[{"name":"Sutures","quantity":100,"unit_price":{"currency":"USD","value":"5.00"}}],"invoice_date":"2017-02-27 PDT","payment_term":{"term_type":"NET_45","due_date":"2017-04-13 PDT"},"tax_calculated_after_discount":false,"tax_inclusive":false,"note":"Medical Invoice 27 Feb, 2017","total_amount":{"currency":"USD","value":"500.00"},"metadata":{"created_date":"2017-02-27 14:42:03 PDT"},"allow_tip":false,"links":[{"rel":"self","href":"https://api.paypal.com/v1/invoicing/invoices/INV2-3RK5-HZV6-35UP-3LLU","method":"GET"},{"rel":"send","href":"https://api.paypal.com/v1/invoicing/invoices/INV2-3RK5-HZV6-35UP-3LLU/send","method":"POST"},{"rel":"update","href":"https://api.paypal.com/v1/invoicing/invoices/INV2-3RK5-HZV6-35UP-3LLU/update","method":"PUT"},{"rel":"delete","href":"https://api.paypal.com/v1/invoicing/invoices/INV2-3RK5-HZV6-35UP-3LLU","method":"DELETE"}]},"links":[{"href":"https://api.paypal.com/v1/notifications/webhooks-events/WH-0G571461Y8752214W-8RU19841BY148894W","rel":"self","method":"GET","encType":"application/json"},{"href":"https://api.paypal.com/v1/notifications/webhooks-events/WH-0G571461Y8752214W-8RU19841BY148894W/resend","rel":"resend","method":"POST","encType":"application/json"}],"event_version":"1.0"}
Custom ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2.WebhookModels.paypal
{
public class Phone
{
public string country_code { get; set; }
public string national_number { get; set; }
}
public class Address
{
public string line1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
}
public class MerchantInfo
{
public string email { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string business_name { get; set; }
public Phone phone { get; set; }
public Address address { get; set; }
}
public class BillingInfo
{
public string email { get; set; }
}
public class Phone2
{
public string country_code { get; set; }
public string national_number { get; set; }
}
public class Address2
{
public string line1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
}
public class ShippingInfo
{
public string first_name { get; set; }
public string last_name { get; set; }
public string business_name { get; set; }
public Phone2 phone { get; set; }
public Address2 address { get; set; }
}
public class UnitPrice
{
public string currency { get; set; }
public string value { get; set; }
}
public class Item
{
public string name { get; set; }
public int quantity { get; set; }
public UnitPrice unit_price { get; set; }
}
public class PaymentTerm
{
public string term_type { get; set; }
public string due_date { get; set; }
}
public class TotalAmount
{
public string currency { get; set; }
public string value { get; set; }
}
public class Metadata
{
public string created_date { get; set; }
}
public class Link
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
}
public class Resource
{
public string id { get; set; }
public string number { get; set; }
public string template_id { get; set; }
public string status { get; set; }
public MerchantInfo merchant_info { get; set; }
public List<BillingInfo> billing_info { get; set; }
public ShippingInfo shipping_info { get; set; }
public List<Item> items { get; set; }
public string invoice_date { get; set; }
public PaymentTerm payment_term { get; set; }
public bool tax_calculated_after_discount { get; set; }
public bool tax_inclusive { get; set; }
public string note { get; set; }
public TotalAmount total_amount { get; set; }
public Metadata metadata { get; set; }
public bool allow_tip { get; set; }
public List<Link> links { get; set; }
}
public class Link2
{
public string href { get; set; }
public string rel { get; set; }
public string method { get; set; }
public string encType { get; set; }
}
public class RootObject
{
public string id { get; set; }
public DateTime create_time { get; set; }
public string resource_type { get; set; }
public string event_type { get; set; }
public string summary { get; set; }
public Resource resource { get; set; }
public List<Link2> links { get; set; }
public string event_version { get; set; }
}
}
Controller:
[HttpPost]
public ActionResult InvoicePaid(RootObject rootObject)
{
using (var ctx = new db_someEntities())
{
}
return Json("ok");
}
I'll assume you're on dotnet core (maybe on a migrated project?) because the code you're posting doesn't have any issues on previous versions of asp.net mvc.
If that's the case, it turns out that on dotnet core the model binding behaviour has changed a little compared to previous versions.
If you want the solution quickly just decorate the parameter of your POST action with [FromBody] attribute. It should work.
[HttpPost]
public ActionResult InvoicePaid([FromBody]RootObject rootObject)
{
using (var ctx = new db_someEntities())
{
}
return Json("ok");
}
The story is a little longer though, and very interesting by the way. If you want the details, I've not found any better resource than this post from Andrew Lock.
UPDATE
I can confirm that if you add the [FromBody] on the action, (I've tested using a bare new asp.net core 2. web app project) it binds the model correctly.
Please let me know if you want me to provide the sources I've used so you can troubleshot from there.
Hope this helps!
Most probably the data being sent it not formatted properly
From comments it was indicated that the data was being sent like
$.post(hookUrl, { testJson: testJson }).done(function (data) { console.log(data); });
consider formatting the data and including the content type
var data = JSON.stringify(testJson); //replace content with your JSObject
$.post(hookUrl, data, null, "application/json")
.done(function (data) { console.log(data); });
Or using the longer syntax
var data = JSON.stringify(testJson); //replace content with your JSObject
$.ajax({
type: "POST",
url: hookUrl,
data: data,
dataType: "application/json",
success: function (data) { console.log(data); }
});
You need to use [FromBody], so MVC knows where to look for the data.
[HttpPost]
public ActionResult InvoicePaid([FromBody]RootObject rootObject)
Related
public class BClass
{
public class RClass
{
public string stjCd { get; set; }
public string lgnm { get; set; }
public string stj { get; set; }
public string dty { get; set; }
public List<object> adadr { get; set; }
public string cxdt { get; set; }
public string gstin { get; set; }
public List<string> nba { get; set; }
public string lstupdt { get; set; }
public string rgdt { get; set; }
public string ctb { get; set; }
public Pradr pradr { get; set; }
public string tradeNam { get; set; }
public string sts { get; set; }
public string ctjCd { get; set; }
public string ctj { get; set; }
}
public class AClass
{
public string id { get; set; }
public string consent { get; set; }
public string consent_text { get; set; }
public int env { get; set; }
public string response_code { get; set; }
public string response_msg { get; set; }
public int transaction_status { get; set; }
public string request_timestamp { get; set; }
public string response_timestamp { get; set; }
public RClass result { get; set; }
}
}
//COntroller
BClass.AClass btr = new BClass.AClass();
var lst = JsonConvert.DeserializeObject<BClass.AClass>(strresult);
btr.response_code = lst.response_code;
btr.response_msg = lst.response_msg;
btr.result.lgnm = lst.result.lgnm;
The property btr.result.lgnm = lst.result.lgnm; Gives null value error object reference not set to instance of an object. but the lst variable has a value in the response received.Please provide suggesion
You can solve this by adding one line into your code.
btr.result = new BClass.RClass(); //This one. You need to initialize instance before assigning anything to it.
btr.result.lgnm = lst.result.lgnm;
or else, you can also create default constructor for class A.
public AClass()
{
result = new RClass();
}
I would suggest you to please have a look at below web resources for naming conventions widely used for c# language.
Properties naming conventions: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members
class naming conventions: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
Assigning this way does not give null reference exception
RClass rclass=new RClass();
rclass.lgnm=lst.result.lgnm
I'm having a hard time passing the value of an object to a model.
I wanted to pass the data from this obj to the model class
SingleTransactResponse obj = JsonConvert.DeserializeObject<SingleTransactResponse>(await response.Content.ReadAsStringAsync());
SaveTransaction(JsonConvert.SerializeObject(obj));
I used this function to get the data from the model and save it to the database
PayoutEntities payoutdb = new PayoutEntities();
public String SaveTransaction(payout_transaction model)
{
payoutdb.payout_transaction.Add(model);
payoutdb.SaveChanges();
return "Success";
}
SingleTransactResponse Class
public class SingleTransactResponse {
public String senderRefId { get; set; }
public String tranRequestDate { get; set; }
public String particulars { get; set; }
public List<Beneficiary> beneficiary { get; set; }
}
Beneficiary Class
public class Beneficiary
{
public String accountNumber { get; set; }
public String name { get; set; }
public List<Address> address { get; set; }
}
Address Class
public class Address
{
public String line1 { get; set; }
public String line2 { get; set; }
public String city { get; set; }
public String province { get; set; }
public String zipCode { get; set; }
public String country { get; set; }
}
payout_transaction class
public partial class payout_transaction
{
public string transid { get; set; }
public string batchid { get; set; }
public string senderRefId { get; set; }
public string requestDate { get; set; }
public string benefName { get; set; }
public string benefacctno { get; set; }
public string status { get; set; }
public string errdesc { get; set; }
public string transaction_fee { get; set; }
}
I'm just having a hard time converting the obj to the model. I've tried JsonConvert.SerializeObject(obj) but it only converts it to string. Is there any possible way to do this or any work around to solve this problem?
you can do like this
var payoutModel = new payout_transaction
{
senderRefId = obj.senderRefId,
requestDate = obj.tranRequestDate,
.... other properties
}
SaveTransaction(payoutModel);
First of all, I'm new to MVC.
I want to display the properties of the JSON response in a html view.
For example, i want to get the number of page likes from the JSON response and display just the number of likes on a page.
Any help is much appreciated :)
//
// GET: /Facebook/
public ActionResult Index()
{
var json = new WebClient().DownloadString("https://graph.facebook.com/google");
JsonConvert.DeserializeObject<RootObject>(json);
return view();
}
public class CategoryList
{
public string id { get; set; }
public string name { get; set; }
}
public class Location
{
public string street { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string zip { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
}
public class Cover
{
public string cover_id { get; set; }
public string source { get; set; }
public int offset_y { get; set; }
public int offset_x { get; set; }
}
public class RootObject
{
public string about { get; set; }
public string awards { get; set; }
public string category { get; set; }
public List<CategoryList> category_list { get; set; }
public int checkins { get; set; }
public string company_overview { get; set; }
public string description { get; set; }
public string founded { get; set; }
public bool is_published { get; set; }
public Location location { get; set; }
public string mission { get; set; }
public string phone { get; set; }
public string products { get; set; }
public int talking_about_count { get; set; }
public string username { get; set; }
public string website { get; set; }
public int were_here_count { get; set; }
public string id { get; set; }
public string name { get; set; }
public string link { get; set; }
public int likes { get; set; }
public Cover cover { get; set; }
}
}
}
Your action should pass the object to the view:
public ActionResult Index()
{
var json = new WebClient().DownloadString("https://graph.facebook.com/google");
var root=JsonConvert.DeserializeObject<RootObject>(json);
return view(root);
}
and then in your view you can show whichever property you want:
#Model RootObject
<html>
<head>
<title>Showing properties</title>
</head>
<body>
#Model.likes likes.
</body>
</html>
This is if you use the Razor syntax.
you're missing
return view(root);
You should pass the object back to view to use it.
you can use JsonResult in mvc 4,
public JsonResult ReturnSomeJson()
{
JsonResult result = new JsonResult();
//Assign some json value to result.
//Allow get is used to get the value in view.
return view(result,AllowGet.True);
}
I was looking for a similar solution and I found it to be a bit different:
[HttpGet]
public JsonResult Index() {
// your code
return Json("some result string or value", JsonRequestBehavior.AllowGet);
}
This outputs "some result string or value" in your browser when you call this action directly.
Assuming this is a normal action inside a controller that
inherits from Controller class.
i have a problem with my join in my asp.net .. i have two database tables.. named APPLICANT and Profile...they have the same fields.. meaning if the Last name in applicant is null the last name is already in profile table. I already connect my program to the applicant table.. but it have so many null fields that have to fetch from the profile data table.... sorry i'm new in asp.net ...
Here's my code in controller:
public View Result Index()
{
var applicants = (from a in db.APPLICANTs
select a).ToList();
return View(applicants);
}
heres my context:
public partial class APPLICANT
{
public int APPLICANT_ID { get; set; }
public Nullable<int> Profile_id { get; set; }
public string APPLICANT_LastName { get; set; }
public string APPLICANT_FirstName { get; set; }
public string APPLICANT_MiddleName { get; set; }
public string APPLICANT_Address { get; set; }
public string APPLICANT_City { get; set; }
public string APPLICANT_ZipCode { get; set; }
public string APPLICANT_Phone { get; set; }
public string APPLICANT_Email { get; set; }
}
public partial class Profile
{
public int PROFILE_ID { get; set; }
public string Applicant_LASTNAME { get; set; }
public string Applicant_FIRSTNAME { get; set; }
public string Applicant_MIDDLENAME { get; set; }
public string Applicant_EMAIL { get; set; }
public string Applicant_PHONE { get; set; }
public string Applicant_ADDRESS { get; set; }
public string Applicant_ZIPCODE { get; set; }
public string Applicant_CITY { get; set; }
}
thanks for those who can help my problem..
I can't understand what i'm doing wrong. Every time I'm getting this error:
The entity or complex type 'BusinessLogic.CompanyWithDivisionCount' cannot be constructed in a LINQ to Entities query.
I need to get info from 'Company' table and divisions count of each company from 'Division' table, and then make PagedList. Here is my 'Company' table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using BusinessLogic.Services;
using BusinessLogic.Models.ValidationAttributes;
namespace BusinessLogic.Models
{
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
}
Here is my domain model:
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
public class CompanyWithDivisionCount: Company // I'm using this
{
public int DivisionCount { get; set; }
}
Here is my controller:
public ActionResult CompaniesList(int? page)
{
var pageNumber = page ?? 1;
var companies = companyService.GetCompaniesWithDivisionsCount2();
var model = companies.ToPagedList(pageNumber, PageSize);
return View(model);
}
And here is my service part:
public IQueryable<CompanyWithDivisionCount> GetCompaniesWithDivisionsCount2()
{
return (from c in dataContext.Companies.AsQueryable()
select new CompanyWithDivisionCount
{
Id = c.Id,
Name = c.Name,
Status = c.Status,
EffectiveDate = c.EffectiveDate,
URL = c.URL,
EAP = c.EAP,
EAPCredentials = c.EAPCredentials,
Comments = c.Comments,
DivisionCount = (int)dataContext.Divisions.Where(b => b.CompanyName == c.Name).Count()
});
}
}
Thanks for help!!!
Creator of PagedList here. This has nothing to do with PagedList, but rather is an Entity Framework issue (I'm no expert on Entity Framework, so can't help you there). To confirm that this is true, write a unit test along the following lines:
[Test]
public void ShouldNotThrowAnException()
{
//arrange
var companies = companyService.GetCompaniesWithDivisionsCount2();
//act
var result = companies.ToList();
//assert
//if this line is reached, we win! no exception on call to .ToList()
}
I would consider changing you data model if possible so that instead of relating Companies to Divisions by name strings, instead use a properly maintained foreign key relationship between the two objects (Divisions should contain a CompanyID foreign key). This has a number of benefits (including performance and data integrity) and will almost certainly make your life easier moving forward if you need to make further changes to you app (or if any company ever decides that it may re-brand it's name).
If you create a proper foreign key relationship then your domain model could look like
public class Company
{
...
public virtual ICollection<Division> Divisions{ get; set; }
public int DivisionCount
{
get
{
return this.Divisions.Count()
}
}
...
}