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.
Related
Data table
I'm very new on asp.net core. I have a concern is how we can insert value by default via model. Such as I have a table as picture attached.
I can get model auto-generated and insert by select Transaction_UserID but it's not practical as normally we will get current user logon ID and pass it as value to that field.
My questions are:
How to implement to insert value generated by code not user via input form.
How and on which part we will calculate that value
Such as my code to set is similar like this will not work as it will not allow property with only set.
//- Set user to first user by default
private long _TransactionUserId = 3;
public long TransactionUserId
{
set
{
_TransactionUserId = value;
}
}
Thank for your support in advanced.
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);
}
}
}
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.
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.
I have a table in my database and one of its columns is in Image data type. I can store Image in database but I can't retrieve it. I want to retrive Image for each logged in user. I used this code:
public ActionResult ShowImage()
{
var userID = GetUserID();
var advert = from ad in StoreDb.Ads where ad.UserId == userID select ad.AdImage;
return File(advert, "Image");
}
But got this error:
Error 2 Argument 1: cannot convert from 'System.Linq.IQueryable' to 'string' C:\Users\Tena\Documents\Visual Studio 2010\Projects\MvcApplication6\MvcApplication6\Controllers\Default3Controller.cs 92 25 MvcApplication6
The problem is that advert is in
System.Linq.IQueryable<>byte[]
format but File needs byte[] format. What should I do now? Any answer is helpful.
Thanks
The problem is that the LINQ query isn't being evaluated and the query as it stands could theoretically return more than one result (hence it's an IQueryable).
In fact the query doesn't look right as presumably there will be more than one advert for a particular user and I wouldn't expect the adverts to be stored according to user in any case, but I don't know anything about your data structure, so I'll just try to help you make the query work and you can refine it later.
Try changing this line:
var advert = from ad in StoreDb.Ads where ad.UserId == userID select ad.AdImage;
to this:
var advert = (from ad in StoreDb.Ads where ad.UserId == userID select ad.AdImage).FirstOrDefault();
I could give you other tips around how to do this, but try that first and see what happens.
I'not sure, this is the way to go for this problem. I usually implement a custom http handler, which expects some id (e.g. userid), connects to the database, fetches the picture and returns a stream of bytes with the correct mime type of the picture.
In the "view" i just create an image tag with the url of the http handler as image source.