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
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
My portal has worked fine for several years but nowadays I have problems with my some codes. I want to update my code but at the first step I have problems with login page. when I use FirstOrDefault I got error on object reference while the list is filled and contains 1 user.
int g = db.sp_GetUserData_ByUserName(model.UserName.Trim()).Count();
//it shows 1
OSUserData userData1 = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
I didn't change this code and It works perfectly on the portal. However, I can't run it on my development server.
I checked again and I found that OSUserData constructor throws exception : Enumeration yielded no result. this is my class code :
public OSUserData()
{
this.OSUploadedFilesMultipleUsers = new HashSet<OSUploadedFilesMultipleUser>();
this.OSSalaryLists = new HashSet<OSSalaryList>();
this.OSUploadedFiles = new HashSet<OSUploadedFile>();
}
public int Id { get; set; }
public string Address { get; set; }
public string BranchCode { get; set; }
public string BranchParentNationalCode { get; set; }
public string CitName { get; set; }
public string City { get; set; }
public string CompanyName { get; set; }
public string CouName { get; set; }
public string Country { get; set; }
public string FaxNo { get; set; }
public string FollowCode { get; set; }
public string Hozeh { get; set; }
public Nullable<bool> IsBranch { get; set; }
public string LoginStatus { get; set; }
public string NationalCode { get; set; }
public string NewEconomicNo { get; set; }
public string Oldeconomicno { get; set; }
public string PostalCode { get; set; }
public string ProIdTTMS { get; set; }
public string ProName { get; set; }
public string Provision { get; set; }
public string RegistrationNo { get; set; }
public string State { get; set; }
public string TaxOfficeCode { get; set; }
public string TaxPayerType { get; set; }
public string TelCode { get; set; }
public string TelNo { get; set; }
public string TprId { get; set; }
public string UserName { get; set; }
public bool Validate { get; set; }
public bool Disabled { get; set; }
public string OwnerShipTypeDesc { get; set; }
public Nullable<byte> OwnerShipTypeCode { get; set; }
public bool Processed { get; set; }
public bool CheckedUser { get; set; }
public bool Blocked { get; set; }
public virtual ICollection<OSUploadedFilesMultipleUser> OSUploadedFilesMultipleUsers { get; set; }
public virtual ICollection<OSSalaryList> OSSalaryLists { get; set; }
public virtual ICollection<OSUploadedFile> OSUploadedFiles { get; set; }
You are trying to add to a null/unreferenced/not initialized object/list. Initialize first the list
List<OSUserData> userData1 = new List<OSUserData>();
Then add it
var user = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
userData1.Add(new OSUserData{
Prop1 = user.Prop1,
Prop2 = user.Prop2,
......
});
Or if you only want one user, just make it var
var user = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
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);
I have two classes which are mentioned below. I am trying to map those through Auto Mapper but it is not working.
public class VMTemplates
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public System.DateTime TimeStamp { get; set; }
public virtual ICollection<VMTemplateGroup> VMTemplateGroup { get; set; }
}
public VMTemplateViewModel()
{
VMTemplateGroup = new List<VMTemplateGroupViewModel>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
[Required(ErrorMessage = "Please Upload File")]
[Display(Name = "Upload File")]
[ValidateFile]
public HttpPostedFileBase TemplateUpload { get; set; }
public System.DateTime TimeStamp { get; set; }
public List<VMTemplateGroupViewModel> VMTemplateGroup { get; set; }
I am using this code to map them
confi.CreateMap<VMTemplateViewModel, VMTemplates>().ReverseMap();
confi.CreateMap<VMTemplateGroupViewModel, VMTemplateGroup>().ReverseMap();
calling code
public VMTemplates GetVMTemplateById(int id)
{
return DataContext.VMTemplates.Include("VMTemplateGroup").Where(a => a.Id == id).FirstOrDefault();
}
This is where exception happens. I get stack overflow exception
public VMTemplateViewModel GetVMTemplateById(int templateId)
{
var result = _vmTemplateRepository.GetVMTemplateById(templateId);
return _autoMapperService.MapEntity<VMTemplateViewModel>(result);
}
I'm doing a simple save of some changes to a database table with about 20 columns and it takes 20 seconds. Retrieving a record is almost instant. I'm not sure why this is happening. Is there something I'm doing wrong or is there a faster way to do this?
db.Entry(EmInf).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Confirm/");
(MVC 4 & SQL 2008 R2 | I should note that other web sites are able to update with far more data much faster BUT they're older programs and aren't using EF. Is this a performance issue with EF? I can't see why because other MVC programs I've done don't seem to have this issue.)
Update: It's a database first setup. Forgot to mention.
Here is the full method:
[HttpPost]
[Authorize]
public ActionResult Edit(Em_Emergency_Info EmInf)
{
try
{
using (var db = new WINDEntities()) {
db.Entry(EmInf).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Confirm/");
}
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
int rec = Convert.ToInt32(User.Identity.Name);
return View(db.Em_Emergency_Info.Find(rec));
}
}
Here is the model:
using System;
using System.Collections.Generic;
public partial class Em_Emergency_Info
{
public int id { get; set; } //This is the primary key.
public string Em_PIn_Key { get; set; }
public string Em_policy_nb { get; set; }
public string Em_Pin_nb { get; set; }
public string Em_First_Name { get; set; }
public string Em_Last_Name { get; set; }
public string Em_Addr1 { get; set; }
public string Em_Addr2 { get; set; }
public string Em_City { get; set; }
public string Em_State { get; set; }
public string Em_Zip { get; set; }
public string Em_Plus4 { get; set; }
public string Em_Phone_Home { get; set; }
public string Em_Phone_Work { get; set; }
public string Em_Mobile { get; set; }
public string Em_Email { get; set; }
public string Em_Fax_Nb { get; set; }
public string Em_Relationship { get; set; }
public string Em_type { get; set; }
public bool EmailOptIn { get; set; }
public bool PhoneOptIn { get; set; }
public bool PushOptIn { get; set; }
public bool FaxOptIn { get; set; }
public string Em_Mobile2 { get; set; }
public string Em_EMail2 { get; set; }
public string Em_Other_Info { get; set; }
public string Em_Primary_Contact { get; set; }
public string Em_Full_Name { get; set; }
}