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.
Related
I got a small problem here. I got a course class and a User. I want to show all the Users inside a Course through the API.
the error i get,
'Object reference not set to an instance of an object.'
And this is my controller method,
var objList = _courseRepo.GetUsers(CourseId);
if (objList == null)
{
return NotFound();
}
var objToShow = new List<ViewCourseDetailsDTO>();
foreach (var obj in objList)
{
objToShow.Add(_mapper.Map<ViewCourseDetailsDTO>(obj));
}
return Ok(objToShow);
The Error i got is inside the Foreach-loop. It says that i need to create an object...
This is how my DTO classes looks like,
public class ViewCourseDetailsDTO
{
public int CourseId { get; set; }
public string CourseTitle { get; set; };
public ICollection<UserDTO>? Users { get; set; } = new List<UserDTO>();
}
And this one,
public class UserDTO
{
public string ID { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
}
Do you think i have to break out the UserDTO somehow? Is it Therefore u think ?
if you want to see my CourseRepository than its here,
public ICollection<Course> GetUsers(int courseId)
{
return _db.Course.Where(c => c.CourseId == courseId).Include(a => a.Users).ToList();
}
Would be really grateful if you could help me out here.
Wohooo I found it, damnit!
On my controller, i forgot to put in mapper here,
public CourseController(ICourseRepository courseRepo, IMapper mapper)
{
_courseRepo = courseRepo;
_mapper = mapper;
}
I had injected it correct at the top but forgot to put it inside there ^
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).
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
I have a class
public class Offer
{
public Int32 OfferId { get; set; }
public string OfferTitle { get; set; }
public string OfferDescription { get; set; }
}
and another class
public class OfferLocationViewModel
{
public Offer Offer { get; set; }
public Int32 InTotalBranch { get; set; }
public Int32 BusinessTotalLocation { get; set; }
}
Now in my controller I have the following
public ActionResult PresentOffers(Guid id)
{
DateTime todaysDate=Utility.getCurrentDateTime();
var rOffers=(from k in dc.GetPresentOffers(id,todaysDate)
select new OfferLocationViewModel()
{
Offer. //I dont get anything here..
}).ToList();
return PartialView();
}
Now the problem is in my controller, I can not access any property of the 'Offer' class !!
I thought, since i am creating a new OfferLocationViewModel() and this has a property of type 'Offer', I will be able to access the properties..But I can not.
Can anyone give me some idea about how to do that?
In a class initializer like new OfferLocationViewModel { ... } you can only set the immediate properties, i.e. 'Offer = new Offer()'.
You can't access the contained type's properties through the initializer.
Though you can initialize the view model's Offer to a new Offer with the given properties like this:
var rOffers = (from k in dc.GetPresentOffers(id,todaysDate)
select new OfferLocationViewModel {
Offer = new Offer {
OfferId = ...,
OfferTitle = ...,
OfferDescription = ...
}
}).ToList();
As a novice am trying my hands on MVC3,razor, EF I have Three connected Tables that I want to produce a view from it. In a simpleton's brief the following are about the tables
PJUsers - ID, memUID(this unique Id from membership),FirstName,LastName
PJAwards - user nominates another user for an award, this links with awardtypesID as foreign key ( awardId,bool:awardok)
PJAwartypes - (awardtypeID, awardName)
The query in the controller is like this
var lists =
from tl in db.PJawards
join u in db.PJUsers on tl.nomineeId equals u.ID into tl_u
join i in db.PJUsers on tl.nominatorId equals i.MemUID into tl_i
where tl.awardOk
orderby tl.awardDated ascending
from u in tl_u.DefaultIfEmpty()
from i in tl_i.DefaultIfEmpty()
select new
{
Status = tl.awardOk,
nomineeFname = u.FirstName,
nomineeLname = u.LastName,
award = tl.PJawards.awardName,
Dated = tl.awardDated,
nominatorFname = i.FirstName,
nominatorLname = i.LastName,
nomineeCountry = u.Citizen,
nomineeResidence = u.Residence,
awardtypeId = tl.ID
};
somewhere i read that i have to construct a model class similar to the query in the controller
{
public class AwardUserInfo
{
public AwardUserInfo() { }
public bool Status { get; set; }
public string nomineeFname { get; set; }
public string nomineeLname { get; set; }
public string award { get; set; }
public string Dated { get; set; }
public string nominatorFname { get; set; }
public string nominatorLname { get; set; }
public string nomineeCountry { get; set; }
public string nomineeResidence { get; set; }
public int awardtypeId { get; set; }
}
}
Please I learn by examples so to be able to help me assume I don't know anything
somewhere i read that i have to construct a model class similar to the query in the controller
Try this.
I guess your ef-model is similar to
So You can create a ViewModel class
public class PJAwardsViewModel
{
public int Id { get; set; }
public string NominatorFName { get; set; }
public string NomineeFname { get; set; }
public string AwardName { get; set; }
public bool IsAwarded { get; set; }
}
It will be also good if You add some service class
public class PJAwardsService
{
public static List<PJAwards> GetAll()
{
using (var context = new YourDBEntities())
{
return context.PJAwards
.Include(x => x.PJUsers)
.Include(x => x.PJUsers1)
.Include(x => x.PJAwartypes).ToList();
}
}
}
(Don't forget to write using System.Data.Entity; )
Then You can add a ViewModelHelper class
public class PJAwardsViewModelHelper
{
public static PJAwardsViewModel PopulatePJAwardsViewModel(PJAwards pjaward)
{
return new PJAwardsViewModel
{
Id = pjaward.Id,
NominatorFName = pjaward.PJUsers.FirstName,
NomineeFname = pjaward.PJUsers1.FirstName,
AwardName = pjaward.PJAwartypes.AwardName,
IsAwarded = pjaward.IsAwarded
};
}
public static List<PJAwardsViewModel> PopulatePJAwardsViewModelList(List<PJAwards> pjawardsList)
{
return pjawardsList.Select(x => PopulatePJAwardsViewModel(x)).ToList();
}
}
At the end Your controller index method will look like this
public ActionResult Index()
{
var pjawards = PJAwardsViewModelHelper.PopulatePJAwardsViewModelList(PJAwardsService.GetAll().ToList());
return View(pjawards);
}
The only thing You should do is add a view (build the project before). Choose PJAwardsViewModel as a Model class and List as a scaffold template.
Enjoy it.
Here is a step by step guide by Steven Sanderson on how to use Asp.net MVC3, EF Code First with MVCScaffolding (powershell automation).
http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/
It is a multipart blog post takes you through the exciting journey of MVC3.
All the best.