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 am using ValueInjecter to map domain classes to my view models. My domain classes are complex. To borrow an example from this question:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
// VIEW MODEL
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PersonId { get; set; }
public int AddressId { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
I have looked at FlatLoopInjection, but it expects the view model classes to be prefixed with nested domain model type like so:
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
public int AddressId { get; set; }
public string AddressCity { get; set; }
public string AddressState { get; set; }
public string AddressZip { get; set; }
}
The OP in the linked question altered his view models to match the convention expected by FlatLoopInjection. I don't want to do that.
How can I map my domain model to the original unprefixed view model? I suspect that I need to override FlatLoopInjection to remove the prefix, but I am not sure where to do this. I have looked at the source for FlatLoopInjection but I am unsure if I need to alter the Match method or the SetValue method.
you don't need flattening, add the map first:
Mapper.AddMap<Person, PersonViewModel>(src =>
{
var res = new PersonViewModel();
res.InjectFrom(src); // maps properties with same name and type
res.InjectFrom(src.Address);
return res;
});
and after that you can call:
var vm = Mapper.Map<PersonViewModel>(person);
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)
I am getting null value for the model on postback.I am not able to find out where I am going wrong.I have seen similar questions but couldn't find any solution yet.
Here is my code:
Controller:
public ActionResult ContactUpdate(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string[] testsplit = id.Split(',');
List<int> intTest = new List<int>();
foreach (string s in testsplit)
intTest.Add(int.Parse(s));
ObjectParameter ObjParam = new ObjectParameter("ErrorCode", 0);
var cont = db.spErrorContactGet(365, ObjParam);
var ToBeUpdated = (from contacts in cont
where intTest.Contains(contacts.ResponseID)
select contacts);
IEnumerable<spErrorContactGet_Result> Update = ToBeUpdated.ToList();
return View(Update);
}
[HttpPost]
public ActionResult ContactUpdate(List<spErrorContactGet_Result> Res)
{
if (Res == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do something
// redirect to another view
}
Here is the model class:
public class spErrorContactGet_Result
{
public int ResponseID { get; set; }
public string ContactAlchemyMessage { get; set; }
public string ContactTeamAlchemyMessage { get; set; }
public string ContactElectronicAddressAlchemyMessage { get; set; }
public string ContactAccountAlchemyMessage { get; set; }
public string CRMContactID { get; set; }
public string InfluenceLevel { get; set; }
public string JobRole { get; set; }
public string Department { get; set; }
public string DepartmentName { get; set; }
public string MobilePhone { get; set; }
public string Email { get; set; }
public string Suffix { get; set; }
public string FaxNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string JobTitle { get; set; }
public string HonorablePrefix { get; set; }
public string Prefix { get; set; }
public string ContactAuthPhoneId { get; set; }
public string ContactAuthDmailId { get; set; }
public string ContactAuthEmailId { get; set; }
public string AllowFax { get; set; }
public string PartnerContactAuthPhoneID { get; set; }
public string PartnerContactAuthDmailID { get; set; }
public string PartnerContactAuthEmailID { get; set; }
public string PrivacyStatementReviewed { get; set; }
public string PreferredLanguage { get; set; }
public string IndWorkPhone { get; set; }
public string FullNamePronunciation { get; set; }
public string CRMOwner { get; set; }
public string KeyContact { get; set; }
public string MarketingAudience { get; set; }
public bool IsSelected { get; set; }
}
}
I am unable to post the view in the right format.
It is likely that structure of your view differs from one that is of your model, they must syntactically match. If you would post your view it could help. BTW there is no 'Postback' in MVC
ASP .NET MVC4
Class #1:
public class F61BPROD
{
public int WPDOCO { get; set; }
public string WPDCTO { get; set; }
public string WPMCU { get; set; }
public string WPLOCN { get; set; }
public string WPDCT { get; set; }
public int WPTRDJ { get; set; }
public string WPKYPR { get; set; }
public string WPLITM { get; set; }
public decimal WPTRQT { get; set; }
public string WPKYFN { get; set; }
public string WPLOTN { get; set; }
public string WPLRP1 { get; set; }
public string WPLRP2 { get; set; }
public string WPLRP3 { get; set; }
public string WPLRP4 { get; set; }
public string WPLRP5 { get; set; }
public string WPLRP6 { get; set; }
public string WPLRP7 { get; set; }
public string WPLRP8 { get; set; }
public string WPLRP9 { get; set; }
public string WPLRP0 { get; set; }
public string WPFLAG { get; set; }
public string WPLOT1 { get; set; }
public string WPLOT2 { get; set; }
}
For one of the properties of Class #1 i need to fetch one of Class #2:
public class JDEItemBasic
{
public int itm { get; set; }
public string litm { get; set; }
public string dsc { get; set; }
public string dsce { get; set; }
public string ean14 { get; set; }
public string cc { get; set; }
public string uom1 { get; set; }
public string uom2 { get; set; }
public int uom1ea { get; set; }
public int bxuom1 { get; set; }
public int uom1gr { get; set; }
}
There is a DAL that gets the above classes. I need to combine these classes a new class that will have most of the properties of the above classes.
Should i create a third class and do the job in BLL?
or should i do it in UI using LINQ to Entities after i fetch them?
Should i create a third class and do the job in BLL?
or should i do it in UI using LINQ to Entities after i fetch them?
That would depend on where you need this class. If it is for displaying purposes then it should live in the UI. This class even has a name in this case: it's called a view model and is what your controller action could pass to the view after querying your DAL layer and projecting the various results to this view model.