MVC 4 System.NullReferenceException: Object reference not set to an instance of an object - asp.net-mvc-4

This is where I'm getting my error.
#foreach(var entry in ViewBag.Entries){...}
I stepped through the program after entering values into a form.
The Entries are hitting the dB and in my controller it showed that the linq code hit the DB but when I returned the view, the object wasn't found?
here is the code in my controller
public ActionResult Index()
{
var mostRecentEntries =
(from entry in _db.Entries
orderby entry.DateAdded descending
select entry).Take(20);
return View();
}
If it'll help you this is coming straight out of a book ASP.net mvc 4 in Action by the Manning company around page 34.

As the error is trying to tell you, ViewBag.Entries is null.
If you want to use something in ViewBag, you need to put it there in the controller.

Related

Pass list from Razor page to code behind to bulk insert using Dapper

So I've created an HTML table on a Razor page as shown below. Basically I'm just calling a method that returns a list and then using a foreach to go create the rows and controls. The part I'm completely lost on is how I go about posting this data back to the server and on the code behind using that data to insert back to SQL Server. I'm using Dapper and I'd like each row of the table to represent a data row, or one object, but how do I get the data from the Razor page passed back as a list of a class? Not sure if my terminology is accurate here but can you model bind on a list of a type? Would appreciate some assistance thanks!
It seems I'm so far off track (or so few people use asp.net core and Dapper) that I'm not getting any help. But someone very helpful marked down my question without commenting - thanks so much.
I realised the key thing I was doing wrong was trying to circumvent model binding, so I created a class/type Rating that represents each row (each column as a property) and then an Assessment type/class that contains a List as one of the properties.
On the Razor page:
#foreach (Comp c in Model.GetComps())
{
count++;
Model.assessment.Ratings.Add(new Rating());
Model.assessment.Ratings[count].AchievedCompetencyID = c.AchievedCompetencyID;
Code behind:
public void OnPost()
{
using (IDbConnection con = new SqlConnection(Startup.conStr))
{
long assessID = con.Insert(assessment);
foreach (Rating r in assessment.Ratings)
{
r.AssessmentID = Convert.ToInt32(assessID);
con.Insert(r);
}
}
}

Saving user ID with Entity Framework

I'm using entity framework v6.2.0 and ASP Net MVC to create a web page to access a database and edit the entries. The overwhelming majority of the code is the basic framework provided for me. The database is connected successfully and entries can be viewed, edited, and deleted. Additionally I have implemented some rudimentary paging, searching, and sorting as instructions are provided by microsoft on how to implement those. The last thing I need to do before the site is truly functional is to pull the userID from the users login and save that as the EnteredBy field before saving any changes or new entries to the table.
if (ModelState.IsValid)
{
string currentUserId = User.Identity.GetUserId();
yasukosKitchen.EnteredBy = currentUserId;
db.YasukosKitchens.Add(yasukosKitchen);
db.SaveChanges();
return RedirectToAction("Index");
}
This code seems very simple, and I added using Microsoft.AspNet.Identity; so it compiles fine. However when I attempt to test this code the EnteredBy field is left blank or null.
My search for information turned up a post suggesting the use of the following line of code.
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
However when I attempt to add that I get an error, the ApplicationUser cannot be found and Users does not exist in this context. The fix for this is probably staring me in the face but my lack of experience and comprehension is killing me.
As suggested: My question is, how do I get and/or correctly add the UserId to my database entry?
If your Database Context has an entry to your YasukosKitchen table; usually something like this,
public virtual DbSet<YasukosKitchen> YasukosKitchens {get; set;}
and YasukosKitchen table has a column 'EnteredBy' (string 128 length), then you can post the value for the logged in user's Id straight from the View.
Add this to the very beginning of the Create view.
#using Microsoft.AspNet.Identity
#using Microsoft.AspNet.Identity.EntityFramework
At the end of the form just before the submit button, add this code.
#Html.HiddenFor(model => model.EnteredBy, new { #Value = User.Identity.GetUserId() })
I'm not sure what is the functionality of 'Users' table.

Preserving the value of ViewData MVC 4

I am working on MVC 4 where i have "ActionResult" method which is of login page, username and password are entered in textbox, based on the username(which is billnumber) after login it should pull the data of that respective billnumber(username), so currently everything is working fine, I am able to get the username from one view and send it to another for further verification, I have stored "username" and "usertypeID" in Viewdata and that value is passed to next view, but the data on ViewData will not stand for longer time, and even if we try to refresh the page multiple times(10 to 20 times), below are the code which i Have used to store and to access
this is where i store the value
public ActionResult ValidateLogIn(FormCollection postedFormData)
{
// codes
TempData["UsrName"] = LoginViewModel.LoginDataModel.UserName;
// codes
}
public ActionResult LandingPage()
{
ViewData["message"] = TempData["UsrName"].ToString();
ViewData["person"] =Convert.ToInt32(TempData["UserTypeID"]);
TempData.Keep();
PatientDetailsViewModel PatientDetailsViewModel = new PatientDetailsViewModel();
String PatID = Convert.ToString(ViewData["message"].ToString());
int PersonType = Convert.ToInt32(ViewData["person"]);
PatientUnderDoctorDetailsViewModel = PatientUnderDoctorDataAccessService.PatientUnderDocLogInEnquiry(PatID);
}
this is where i store it on viewdata
ViewData["message"] = TempData["UsrName"].ToString();
ViewData["person"] =Convert.ToInt32(TempData["UserTypeID"]);
TempData.Keep();
AND HERE IS WHERE I GET VALUES FROM VIEWDATA
String PatID = Convert.ToString(ViewData["message"].ToString());
int PersonType = Convert.ToInt32(ViewData["person"]);
I am passing PatID and PersonType as parameter to next method,
at beginning I wasn't using TempData.keep(); so when I refresh the page atleast once used to get error, tried searching and found TempData but i believe it is not much efficient for longer time, if I left application idle for 5 mins and then refreshes the page once , it generates error message since tempdata is empty(null)
WHAT I NEED
let me know is there any mistake i have done, or is there any better way to fix this issue, where data can be stored in variable until I quit the application
I hope this link will help you State Management In MVC
Don't use Temp data for this. it will be lost when the app pool refreshes or if you use another process (web garden).
User.Identity.Name will return the name of a validated user.
If you are passing data around you should be using Models and not ViewData or TempData or ViewBag.

Editing User Profile Data in SimpleMembership

I am using SimpleMembership in an MVC4 web app. I can't figure out how to edit the profile information. I thought I could do it just as you do any other table.
[HttpPost]
public ActionResult EditUser(UserProfile user)
{
if (ModelState.IsValid)
{
udb.Entry(user).State = EntityState.Modified;
udb.SaveChanges();
return RedirectToAction("Index");
}
But I get an error saying entity state does not exist in the current context. My context is defined as follows at the top of the controller.
private UsersContext udb = new UsersContext();
I can find plenty of references on access profile data but nothing for editing the data. How can I save the edited UserProfile data back to the db?
EDIT: I was able to resolve the entityState error -- I had to include system.data and system.data.entity. However now when I run I get an error on edit which says unexpected number of rows modified (0). and points to the udb.SaveChanges() line. Still can't figure out how to modify UserProfile data elements.
Simple answer. I needed to set all the fields for the Model in my view. I was only allowing the user to change 4 out of the 6 so two were not being set.
I thought when you pass the model to the view, the view would pass the same field values onto the action if they were not set in the view. For example: if I set FirstName in the view but not UserName the original UserName that was sent to the view would be passed to the Model. That appears not to be the case. For all the items in the model I did not allow them to change in the view I had to set hidden fields to set the fields so a complete model was sent.
It may be better to set individual fields but I am not sure how to do that yet and that was not the question.

EF : MVC : ASP: TPH Error - Store update, insert, or delete ... number of rows (0). Entities ... modified or deleted ... Refresh ObjectStateManager

Error Message: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
Hello All,
I've created a Code First TPH(Table Per Hierarchy) within MVC and EF with a SQL compact db.
Here's the Class diagram/Hierarchy:
Class Diagram
Client and SalesRep both inherit the BaseUser class. The Key is "UserID" and it's coded with the Data Annotation [Key](I'm aware that 'ID' should set it as well)
Here's where I'm at: I can seed the database with a few entries. When I try to set the "UserID" in the seeding method it seems to ignore it and just apply the UserID in numerical order...(Seems ok to me?)
furthermore here's my DbContext
public class SiteDB:DbContext
{
public DbSet<BaseUser> AllUsers { get; set; }//enable TPH
public DbSet<SalesRep> SalesReps { get; set; }
public DbSet<Client> Clients { get; set; }
}
Next,
I have created a controller for Clients -> ClientsController with strongly typed Razor Views. With this. I now have a CRUD for the Clients. I can create new Clients without any issue, but when I try to edit a Client entry, I get the error message stated above.
I did notice something interesting I stepped through the code and the error is happening on the db.SaveChanges();
When the client is passed back into the ActionResult Edit method the UserID=0! Bizarre? I'm not sure if this is a bug or if it's an actual issue that's causing this.
UserID=0
Your help with this is appreciated. Thanks!
To modify an entity you need to get it from the database: when you pass back the modified values in the Edit action you need to retrive the entity from the db object, getting it by ID, apply the modified values and save it.
Here an example:
public ActionResult Edit(int id, MyModel model){
using (SiteDBdb = new SiteDB()){
Client cl = (from c in db.Clients where c.id == id select c).First();
cl.MyProp = model.MyProp;
...
db.SaveChanges();
}
...
}