Data from model not passing to view - c#

I have some code that is functioning oddly and was wondering if anyone else hase come across this issue.
I have a view model that collects data from a database via a stored procedure and a vb object (no I do not know vb this is legacy)
When I execute the program the data is collected as expected via the controller. When I debug it I can see all of my parameters populating with information. However when it comes to the view it says that the parameters are null. I have included my code
Models:
public class PersonIncomeViewModel
{
public string IncomeTypeDesc { get; set; }
public string IncomeDesc { get; set; }
public string Income { get; set; }
}
public class PersonIncomeListViewModel
{
public int? PersonId { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonIncomeListViewModel()
{
Incomes = new List<PersonIncomeListItem>();
}
}
public class PersonLookupViewModel : Queue.QueueViewModel
{
public int Action { get; set; }
public bool ShowAdvancedFilters { get; set; }
//Person Search Variables
[Display(Name = #"Search")]
public string SpecialSearch { get; set; }
[Display(Name = #"Person Id")]
public int? PersonId { get; set; }
[Display(Name = #"Full Name")]
public string FullName { get; set; }
[Display(Name = #"SSN")]
public string SSN { get; set; }
public string AddressStatus { get; set; }
public string EmploymentStatus { get; set; }
public PersonIncomeViewModel Income { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonLookupViewModel()
{
Income = new PersonIncomeViewModel();
Incomes = new List<PersonIncomeListItem>();
}
}
Controller:
public ActionResult _Income(int id)
{
var vm = new PersonLookupViewModel();
var personManager = new dtPerson_v10_r1.Manager( ref mobjSecurity);
//var person = personManager.GetPersonObject((int)id, vIncludeIncomes: true);
var person = personManager.GetPersonObject(id, vIncludeIncomes: true);
var look = JsonConvert.SerializeObject(person.Incomes);
foreach (dtPerson_v10_r1.Income income in person.Incomes)
{
if (income.IncomeType_ID == 0)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Unknown",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 1)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Alimony",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 2)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Child Support",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
}
return PartialView(vm);
}
View:
#using dtDataTools_v10_r1
#using ds_iDMS.Models.Person
#model ds_iDMS.Models.Person.PersonLookupViewModel
#{
var format = new dtDataTools_v10_r1.CustomFormat();
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
}
using (Html.DSResponsiveRow(numberOfInputs: ExtensionMethods.NumberOfInputs.TwoInputs))
{
using (Html.DSCard(ExtensionMethods.Icon.CustomText, iconInitials: newInitials, color: ExtensionMethods.Colors.PrimaryBlue))
{
<div>#Model.Income.IncomeTypeDesc</div>
<div>#Model.Income.IncomeDesc</div>
<div>#Model.Income.Income</div>
}
}
There are some extensions that we have built but they are irrelevant to the issue
The line that errors out is this one:
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
Which drives all of the extension methods on the view and as I run the debugger over it all of the parameters read null, however like I said when I run the debugger and check them in the controller they are populated properly.
Sorry about the long post but I wanted to ensure all the detail was there

This is how to pass the Object model to your Partial View
return PartialView("YourViewName", vm);
or using the Views path
return PartialView("~/YourView.cshtml", vm);
EDIT
Try starting your Action Method like this
var vm= new Person();
vm.PersonLookupViewModel = new PersonLookupViewModel();

Problem solved I had issues with some of my vb objects and had the vb person take a look at them and she fixed them.
Thank you for all the help
EDIT
What had to happen is the vb object had to be re-written and my logic was just fine as it was in the beginning. I marked the one response to my question as the answer because had it been in true MVC without vb objects attached to it, that would have worked perfectly

Related

Separate Model with List

I want to return a list of links to a web page when it loads. Right now I have a model called SsoLink.cs bound to the page. I would like to return a list, so I have created another model called SsoLinks.cs that has a List. In my helper function, I keep getting "object not set to an instance of an object".
SsoLink.cs
public class SsoLink
{
public enum TypesOfLinks
{
[Display(Name="Please Select a Type")]
Types,
Collaboration,
[Display(Name="Backups & Storage")]
Backups_Storage,
Development,
[Display(Name="Cloud Services")]
Cloud_Services,
[Display(Name="Human Resources")]
Human_Resources,
Analytics
}
public string Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Owner { get; set; }
public string OwnerEmail { get; set; }
public string LinkDescription { get; set; }
public TypesOfLinks LinkType { get; set; }
}
SsoLinks.cs
public class SsoLinks
{
public List<SsoLink> Links {get; set;}
}
GetLinksHelper.cs
public partial class SsoLinkHelper
{
public static SsoLinks GetLinks()
{
var ssoList = new SsoLinks();
try
{
//search the index for all sso entries
var searchResponse = _client.Search<SsoLink>(s => s
.Index(_ssoLinkIndex)
.Size(500)
.Query(q => q
.MatchAll()
)
);
if (searchResponse.Documents.Count == 0)
{
return ssoList;
}
ssoList.Links.AddRange(searchResponse.Hits.Select(hit => new SsoLink() {Id = hit.Source.Id, Name = hit.Source.Name, Url = hit.Source.Url, Owner = hit.Source.Owner}));
return ssoList;
}
catch (Exception e)
{
Log.Error(e, "Web.Helpers.SsoLinkHelper.GetLinks");
return ssoList;
}
}
}
While debugging, It is failing at SsoLinks.Links.AddRange(etc). How can I add a new SsoLink to the ssoList for every item found in my query?
Edit: Here is a screenshot of the error while debugging.
The null reference exception looks like it comes from ssoList.Links being null when calling AddRange on it, so it needs to be initialized to a new instance of List<SsoLink> before calling AddRange().
Russ's answer led me down the right path, I ended up just needing to change my view to:
#model List<SharedModels.Models.SsoLink>
rather than
#model SharedModels.Models.SsoLink
and do away with the SsoLinks model.

New class selected by LINQ query, how to transfer to another model?

I'm really not understanding this as I've only dabbled in MVC and C#. I apologize if my terminology is wrong or confusing, I will do my best to answer questions. I have a couple models like so:
public class DataSharingModels
{
public string ReferenceID { get; set; }
public NBTC NBTCGroup { get; set; }
public Contractors ContractorsGroup { get; set; }
public Coordinators CoordinatorsGroup { get; set; }
public NGO NGOGroup { get; set; }
public Public PublicGroup { get; set; }
public SelectList FA_RA_List { get; set; }
}
public class NBTC
{
public String NBTC_FA_Centroid { get; set; }
public String NBTC_FA_Bound { get; set; }
public String NBTC_RA_Centroid { get; set; }
//more properties...
}
The DataSharingModels class contains the public NBTC NBTCGroup property. It is not public List<NBTC> NBTCGroup because there will only be one produced per instance of the controller being hit.
Now in my controller, I have a LINQ statement that selects a new NBTC class:
var nbtcVals = (from ds in db.SharingPermissions
where ds.FocalRefID.ToString() == ReferenceID
&& ds.ShareGroup == "NBTC"
select new NBTC
{
NBTC_FA_Centroid = ds.CIP_FA_Centroid,
NBTC_FA_Bound = ds.CIP_FA_Boundary,
NBTC_RA_Centroid = ds.CIP_RA_Centroid,
//more properties...
});
Where I'm going wrong is I would like to add that to my DataSharingModels model. I thought the nbtcVals type would be NBTC, but it's IQueryable<##.Models.NBTC>. I understand I could do this, but it seems redundant:
DataSharingModels dsm = new DataSharingModels();
if (nbtcVals.Any())
{
foreach (var i in nbtcVals)
{
dsm.NBTCGroup.NBTC_FA_Centroid = i.NBTC_FA_Centroid;
dsm.NBTCGroup.NBTC_FA_Boundary = i.NBTC_FA_Bound;
dsm.NBTCGroup.NBTC_RA_Centroid = i.NBTC_RA_Centroid;
//more properties...
}
}
What is a more direct way to do this? There must be one. I supposed I could also return an anonymous type in the LINQ query and then assign each property in the foreach like dsm.NBTCGroup.NBTC_RA_Centroid = i.NBTC_RA_Centroid but that seems the same as the other way.
var nbtcgroup = (from ds in db.SharingPermissions
where ds.FocalRefID.ToString() == ReferenceID
&& ds.ShareGroup == "NBTC"
select new NBTC
{
NBTC_FA_Centroid = ds.CIP_FA_Centroid,
NBTC_FA_Bound = ds.CIP_FA_Boundary,
NBTC_RA_Centroid = ds.CIP_RA_Centroid,
//more properties...
})
.OrderByDescending(n => n.Id) // or some other property that could identify sorting
.FirstOrDefault();
This one has a translation to SQL (LIMIT or TOP depending on backend).

System.Web.Mvc.WebViewPage<T>.Model.get returned null

I am trying to create my first ASP.NET MVC application but since two days I cannot solve my problem.
I am using Entity Framework Code First approach. I want to create DropDownListFor but there is always this error:
System.NullReferenceException
System.Web.Mvc.WebViewPage.Model.get returned null.
My Model:
public class Animals
{
public int AnimalsId { get; set; }
public int ClientsId { get; set; }
public string Name { get; set; }
public int TypesId { get; set; }
public float Age { get; set; }
public float Weight { get; set; }
public virtual Types Types { get; set; }
public IEnumerable<Clients> ClientsList { get; set; }
public virtual ICollection<BookVisit> AnimalsVisits { get; set; }
}
My controller:
public ActionResult Create([Bind(Include = "AnimalsId, ClientsId, Name, TypesId, Age, Weight")] Animals animals)
{
var person = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo", Surname = "Werner", Email = "timo.werner#gmail.com", Phone = 123123123 }
};
var animalsView = new Animals
{
ClientsList = person.Select(x => new Clients
{
ClientsId = x.ClientsId
})
};
if (ModelState.IsValid)
{
db.Animals.Add(animals);
db.SaveChanges();
return RedirectToAction("List", "Animal");
}
return View(animalsView);
}
My view (only #model and dropdown):
#model xyz.Models.Animals
#Html.DropDownListFor(model => model.ClientsId, new SelectList(Model.ClientsList, "ClientsId", "Name", "Surname", "Email", "Phone"))
Could you please take a look ?
From the comments, it looks like you are not passing a valid view model object to the view. Your view code is expecting a valid model passed to it and the helper methods are using different properties of that.
public ActionResult Create()
{
var clients = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo" },
new Clients { ClientsId = 51, Name = "Microsoft" }
};
var vm = new Animals
{
ClientsList = clients
};
return View(vm);
}
Also your current code which calls the DropDownListFor is wrong. When you create a SelectList from a collection, you have to pass the dataValue field and dataText fields.
#model Animals
#Html.DropDownListFor(model => model.ClientsId,
new SelectList(Model.ClientsList, "ClientsId", "Name"))
This error may also be caused by trying to use a null model in razor view. In such case check if the model is null or not before using it as shown below:
#if (Model != null) {
<a onclick="get('#Url.Action("GetEmployee", "DemoController")', #Model.Id)" ></a>
}

Entity Framework 5 - LINQ syntax error

I have the following code where I am creating a IList that I need to filter by the data in another list called List. The locations list represents the locations a user is allowed to view based on their permissions. I am new to LINQ and am confused with error I get (C# Unknown method "Where(?)" of "System.Ling.IQueryable". I have tried various syntax arrangement using either Contains() and Any() or both to no avail. I feel like it's something very basic that I don't understand about doing this. Here is the code:
----- users locations
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Decking.Models
{
public class locations
{
[Key]
public string org_id { get; set; }
}
}
///////// here is the view model
using System.ComponentModel.DataAnnotations;
using System;
namespace Decking.Models
{
public class InventoryViewModel
{
[Key]
public int id { get; set; }
public DateTime metric_dt { get; set; }
public int? item_id { get; set; }
public int? loc_type_id { get; set; }
public string trlr_nbr { get; set; }
public string user_id { get; set; }
public string org_id { get; set; }
public Double numerator { get; set; }
//these are the child entities
[UIHint("ClientItem")]
public ItemViewModel Items
{
get;
set;
}
[UIHint("ClientLocTypes")]
public LocTypesViewModel LocTypes
{
get;
set;
}
[UIHint("ClientOrgsByUser")]
public OrgsByUserViewModel OrgsByUser
{
get;
set;
}
}
}
///////// code to populate the view model
public IList<InventoryViewModel> GetAll(List<locations> locs)
{
IList<InventoryViewModel> result = new List<InventoryViewModel>();
result = entities.inventory.Select(inventory => new
InventoryViewModel
{
id = inventory.id,
metric_dt = inventory.metric_dt,
item_id = inventory.item_id,
loc_type_id = inventory.loc_type_id,
trlr_nbr = inventory.trlr_nbr,
org_id = inventory.org_id,
numerator = inventory.numerator,
user_id = inventory.user_id,
Items = new ItemViewModel()
{
item_id = inventory.items.item_id,
item_desc = inventory.items.item_desc,
},
LocTypes = new LocTypesViewModel()
{
loc_type_id = inventory.loc_types.loc_type_id,
loc_desc = inventory.loc_types.loc_desc,
},
OrgsByUser = new OrgsByUserViewModel()
{
user_id = inventory.user_id,
//mgr_emp_nbr = inventory.mgr,
org_id = inventory.org_id,
},
}).Where(e => e.metric_dt == DateTime.Today && e.org_id
==locs.Any(o=>o.org_id)) // this doesn't work
//}).Where(e => e.metric_dt == DateTime.Today && e.org_id == "SGF") //
this works
.ToList();
return result;
}
Any help you can provide would be greatly appreciated! Thank so much!
The problem is in e.org_id == locs.Any(o=>o.org_id). As I can see in your working example, your org_id is a string.
I guess what you are trying to do is .Where(e => e.metric_dt == DateTime.Today && locs.Any(o=>o.org_id == e.org_id))

Properties of referenced class not showing during internal assignment

I have below ItemCountAmount.cs class.
public class ItemCountAmount
{
public int Count { get; set; }
public string Amount { get; set; }
}
and I am referencing it in one more class ChartData.cs as below:
public class ChartData
{
public ChartData()
{
Purchase = Stocks = Sales = new ItemCountAmount();
}
public string period { get; set; }
public ItemCountAmount Purchase { get; set; }
public ItemCountAmount Stocks { get; set; }
public ItemCountAmount Sales { get; set; }
}
Now when I try to assign the values for the ChartData properties, it isn't recognizing or available. Compile time exception will occur in VS.
var model = new ChartData
{
period = yearMonth,
Purchase.Count = await purchase.CountAsync(x => x.order_date.Month == mnth && x.order_date.Year == yr),
}
But Purchase.Count or Purchase.Amount isn't identified here where in if I try it as
var model=new ChartData();
model.Purchase.Count = .....;
model.Purchase.Amount = .....;
.......
it works fine, I mean, property Count and Amount is identified. I am still not getting why the first method is not able to identify the properties from ItemCountAmount.cs class which is referenced in ChartData. Any specific reasons for this?
I don't believe the C# object initialiser supports that syntax, however, you can just do this. I am not sure whether this would result in two constructions and assignemnts to Purchase though, you could break point that yourself and see.
var model = new ChartData
{
Purchase = new ItemCountAmount
{
count = await purchase.CountAsync(x => x.order_date.Month == mnth && x.order_date.Year == yr)
}
}

Categories