How read data from the another table in c# - c#

I have created a project in ASP.NET MVC 5 with two tables.
This is the table's structure:
CREATE TABLE [dbo].[User]
(
[UserID] INT IDENTITY (1, 1) NOT NULL,
[FirstName] VARCHAR (50) NOT NULL,
[LastName] VARCHAR (50) NOT NULL,
[Email] VARCHAR (256) NOT NULL,
[DateOfBirth] DATE NULL,
[Password] NVARCHAR (MAX) NOT NULL,
[IsEmailVerified] BIT NOT NULL,
[ActivationCode] UNIQUEIDENTIFIER NOT NULL,
[ResetPasswordCode] NVARCHAR (100) NULL,
PRIMARY KEY CLUSTERED ([UserID] ASC)
);
CREATE TABLE [dbo].[OrderDetails]
(
[OrderID] INT NOT NULL IDENTITY,
[User_ID] INT NOT NULL,
[OrderDate] DATE NULL,
[A_ChickenChop_BP] INT NOT NULL,
[A_ChickenChop_M] INT NOT NULL,
[A_Spaghetti_AH] INT NOT NULL,
[A_Spaghetti_P] INT NOT NULL,
[A_Spaghetti_S] INT NOT NULL,
[A_ChickenRice_CB] INT NOT NULL,
[A_ChickenRice_CW] INT NOT NULL,
[A_ChickenRice_D] INT NOT NULL,
[A_WantanMee_IS] INT NOT NULL,
[A_WantanMee_NS] INT NOT NULL,
CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED ([OrderID] ASC),
CONSTRAINT [FK_OrderDetails_User]
FOREIGN KEY ([User_ID]) REFERENCES [dbo].[User] ([UserID])
);
As the project is login needed so the UserID has been set up like 1,2,3,.... After login that, user can order the food from the program and I want to have a view that can display the UserID from the User table. So the code I write is like this:
public class OrderController : Controller
{
// GET: Order
[HttpGet]
public ActionResult orderUser()
{
return View();
}
[HttpPost]
public ActionResult orderUser(User orderUser)
{
using (myDatabaseEntities myDatabase = new myDatabaseEntities())
{
var userID = myDatabase.OrderDetails.Where(a => a.User_ID == orderUser.UserID).FirstOrDefault();
}
return View(orderUser);
}
}
The User_ID is the ID I want it same like the UserID from the user table. So the userid in the controller I make that orderDetails's User_ID is same to the User's UserID but it doesn't work! And the view I display in program is empty like it is read a null data.
I want make the User_ID from OrderDetails table will read the UserID table here.
Where is the mistake I make?
#model Food_Founder.Models.OrderDetail
#{
ViewBag.Title = "orderUser";
}
<h2>orderUser</h2>
#HttpContext.Current.User.Identity.Name
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>OrderDetail</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.OrderID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OrderID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.User_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User_ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OrderDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_ChickenChop_BP, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_ChickenChop_BP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_ChickenChop_BP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_ChickenChop_M, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_ChickenChop_M, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_ChickenChop_M, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_Spaghetti_AH, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_Spaghetti_AH, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_Spaghetti_AH, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_Spaghetti_P, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_Spaghetti_P, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_Spaghetti_P, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_Spaghetti_S, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_Spaghetti_S, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_Spaghetti_S, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_ChickenRice_CB, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_ChickenRice_CB, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_ChickenRice_CB, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_ChickenRice_CW, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_ChickenRice_CW, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_ChickenRice_CW, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_ChickenRice_D, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_ChickenRice_D, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_ChickenRice_D, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_WantanMee_IS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_WantanMee_IS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_WantanMee_IS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.A_WantanMee_NS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.A_WantanMee_NS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.A_WantanMee_NS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Above the code is the view code and it is like this.
As you can see there is a userid that I circle it already. I want make that it will display the data of the User's userid

If I understand your question correctly, what you want to do is return a view using the OrderDetails that matches the UserId passed in through the User argument. The first problem I see with your code is you're using variable name "orderUser" both as your Action method name, and as parameter that is passed in. While your compiler won't complain about it, other programmers will give you a look like you just wrote 1000 lines of spaghetti code and didn't indent your loops and if statements. Using duplicate names for different items in the same method makes your code less readable, and less maintainable. If it helps, try being more verbose in your naming conventions such as, "UserAction," or "userWithOrder."
Second problem, while your entity framework statement is correct, (you're pulling the entire data record, not just the UserId; the variable should be named, UserDetails) you have a scope problem with the using statement. The "UserId" record will drop out of scope outside of the braces that define the using statement, so you must use it before execution leaves the using scope. Alternatively, you can assign the record to a local variable defined outside of the using's scope.
Finally, the way this is written, all you are doing is calling your method and passing in a user parameter, and then returning that same user parameter to the view. What what are your views bound to, a User model or a Details model? You'll probably need a view for both, or even better consider setting up a partial views.
This is how your code should look if I understand what you're trying to do:
[HttpPost]
public ActionResult orderUser(User userWithOrder)
{
using (myDatabaseEntities myDatabase = new myDatabaseEntities())
{
var orderDetails = myDatabase.OrderDetails.Where(a => a.User_ID == userWithOrder.UserID).FirstOrDefault();
return View(orderDetails) //It is OK to return from within a using statement; the using will close and dispose as needed.
}
}
You should include the code for your views, otherwise, I'm just guessing on what you're attempting to display.

You are passing an User Object as parameter and i believe this User object is currently logged user of the system. If you are passing logged user object correctly, your code should works fine if there is an order placed by that user. And if that user doesn't have an order then it will return null.
So you have to check,
Are you are passing right object to that Function.
Is there any order is in the OrderDetails table associated with that user.
Check your PlaceOrder method where you put entry to OrderDetails table and make sure you are inserting correct USER_ID to OrderDetails table
Its a problem of debugging i guess

Related

How to fix a "System.ArgumentException: 'Value cannot be null or empty. Parameter name: name'" in a MVC app?

I've been working on a summer project where we have to create a portfolio web app where someone can look through a number of potential candidates and select the best one. I've created a SQL database and within there is information and how confident they are in a programming language with a number from 0 - 5. I've created the MVC app and tried to create a new candidate but I am getting this error and have no previous experience coding in this language so am unsure on what to do. Here is my code:
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Candidate</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.First_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.First_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.First_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Last_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Last_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Last_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date_of_birth, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date_of_birth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date_of_birth, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.C__NET___ASP, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.C__NET___ASP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.C__NET___ASP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CSS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CSS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CSS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HTML, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HTML, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HTML, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Java, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Java, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Java, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.JavaScript, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.JavaScript, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.JavaScript, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Python, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Python, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Python, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Python_Flask, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Python_Flask, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Python_Flask, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Any help to fix this issue or come at this project in another way would be amazing!
It is caused by __ (double underscores) in the variable name C__NET___ASP.
You can use C_NET_ASP or CNetAsp instead to solve the issue.
I found similar error reported for ASP.NET Core: https://github.com/dotnet/aspnetcore/issues/18913

Can't save data into multiple tables using ASP.NET EF6

On a page on my website a person can change information about a device.
This data comes from 2 different tables. Saving data into the DeviceStatus table is no problem.
But for some reason I can't save the Active field into the concremodeDevice table. Saving all other data from this table is no problem.
Code:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,DeviceConfig_id,Device_statustypes_id,ConcremoteDevice_id,Employee_1,Employee_2,Sign_Date,Active")] DeviceStatus deviceStatus, ConcremoteDevice concremoteDevice)
{
var Conn = (from d in db.DeviceStatus
join s in db.Device_statustypes on d.Device_statustypes_id equals s.id
join b in db.ConcremoteDevice on d.ConcremoteDevice_id equals b.id
join c in db.DeviceConfig on d.DeviceConfig_id equals c.Device_config_id
select new { s.id, Model = d.id });
if (ModelState.IsValid)
{
db.Entry(deviceStatus).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// ViewBag.device_type_id = new SelectList(db.DeviceType, "device_type_id", "device_type", concremoteDevice.id);
return View(deviceStatus);
}
Page:
#model ConcremoteDeviceManagment.Models.DeviceStatus
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ConcremoteDevice</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
#Html.HiddenFor(model => model.DeviceConfig_id)
#Html.HiddenFor(model => model.Device_statustypes_id)
<div class="form-group">
#Html.Label("Serie nummer", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConcremoteDevice_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConcremoteDevice_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Device Type", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.DeviceConfig.DeviceType.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DeviceConfig.DeviceType.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Config ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DeviceConfig.Device_config_id, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.Label("Medewerker 1", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Medewerker 2", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Signeer datum", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sign_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sign_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Huidige status", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StatusList", null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Device_Statustypes.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("In Gebruik", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-10 checkbox">
#Html.EditorFor(model => model.ConcremoteDevice.Active)
#Html.ValidationMessageFor(model => model.ConcremoteDevice.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
Table:
CREATE TABLE [dbo].[ConcremoteDevice] (
[id] NVARCHAR (50) NOT NULL,
[Active] BIT NULL,
CONSTRAINT [PK_ConcremoteDevice] PRIMARY KEY CLUSTERED ([id] ASC) WITH (FILLFACTOR = 65)
);
So my question is if someone knows why I can't save Active.
As suggested by pinkfloydx33 in the comments I have at some point also tried to set the state of concremodeDevice, but this gave me the next error:
The key field 'id' cannot have a value of null. A non-null value is required for the key fields defined on type 'ConcremoteDevice'
BTW, don't know if ASP.NET of EF6 has anything to do with this, but included it just to be sure.
Try the following:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,DeviceConfig_id,Device_statustypes_id,ConcremoteDevice_id,Employee_1,Employee_2,Device_statustypes_id,Sign_Date,Active")] DeviceStatus deviceStatus, ConcremoteDevice concremoteDevice)
{
if (ModelState.IsValid)
{
db.Entry(deviceStatus).State = EntityState.Modified;
db.Entry(concremoteDevice).State = EntityState.Modified;
db.SaveChanges();
TempData["AlertMessage"] = "Device Edited Successfully";
return RedirectToAction("Index");
}
return View(deviceStatus);
}
And view:
<div class="form-horizontal">
<h4>ConcremoteDevice</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
#Html.HiddenFor(model => model.DeviceConfig_id)
#Html.HiddenFor(model => model.Device_statustypes_id)
#Html.HiddenFor(model => model.ConcremoteDevice.id)

Pass last created id from action to a partial view (asp.net mvc)

I have a little problem that I'm stuck on. I have 2 tables: tbl_NIR and tbl_I_O,
tbl_I_O has a foreign key NirID, so I know which nir got that i_o.
I have an action Add and view, there I insert nir data into the database. Add action returns PartialView. In that PartialView I have new view for tbl_I_O.
I need to somehow get the last ID inserted which I should somehow get after I insert data in Add action. How can you pass ID from Add action to tbl_I_O partial view? I viewed this link and others but with no luck: "Asp.Net mvc - pass last created id from action to partial view".
Actions:
[HttpPost]
public ActionResult Add(BOL1.tbl_NIR nir)
{
try
{
if (ModelState.IsValid)
{
db.tbl_NIR.Add(nir);
db.SaveChanges();
//var ni = db.tbl_NIR.OrderByDescending(x => x.ID).FirstOrDefault().ID;
TempData["Msg"] = "Created Successfully!";
return RedirectToAction("AddIO", nir);
//return RedirectToAction("AddIO", new { id = ni });
//return RedirectToAction("AddIO", "AddIO", new { id = ni });
}
return View(nir);
and the ohter:
[HttpGet]
public ActionResult AddIO()
{
//var ni = db.tbl_I_O.OrderByDescending(x => x.NirID).FirstOrDefault().NirID;
//return View(ni);
return View();
}
[HttpPost]
public ActionResult AddIO(BOL1.tbl_I_O oi)
//public ActionResult AddIO(BOL1.tbl_I_O oi, int ID)
{
try
{
if (ModelState.IsValid)
{
db.tbl_I_O.Add(oi);
db.SaveChanges();
TempData["Msg"] = "Created Successfully!";
return RedirectToAction("Index");
}
return View(oi);
}
and this is the part of code from my view where I need to display the last inserted ID from tbl_NIR (action Add) to tbl_I_O (action AddIO partial view):
<div class="form-group">
#Html.LabelFor(model => model.NirID, "Nir ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("NirID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NirID, "", new { #class = "text-danger" })
</div>
</div>
So any help on it is really appriciated. Sorry for any bad spelling!
Here is my update on this (the view and the partial view):
#model BOL1.tbl_NIR
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#*#{int i = 0;}*#
<div class="form-horizontal">
<h2>Add New</h2>
<br />
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Number, new { htmlAttributes = new { #class = "form-control" } })
#*<span>#(++i)</span>*#
#Html.ValidationMessageFor(model => model.Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#*I 'ved commented this section because it displays the partial view in the same view as VIEW (Add controller) and I don't want that, I want them to be on separate views.*#
#*<div class="form-group">
#Html.Partial("AddIO", new BOL1.tbl_I_O())
</div>*#
<div>
#Html.ActionLink(" Back to List", "Index", null, new { #class = "glyphicon glyphicon-chevron-left" })
</div>
and the partial view:
#model BOL1.tbl_I_O
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<br />
<h5>Add new Entry or Exit</h5>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.NirID, "Nir ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("NirID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NirID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TipID, "Type ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.TipID, (IEnumerable<SelectListItem>)ViewBag.TID, new { #class = "form-control" })*#
#Html.EditorFor(model => model.TipID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TipID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SupplierID, "Supplier ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.SupplierID, (IEnumerable<SelectListItem>)ViewBag.SID, new { #class = "form-control" })*#
#Html.EditorFor(model => model.SupplierID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SupplierID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductID, "Product ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.ProductID, (IEnumerable<SelectListItem>)ViewBag.PID, new { #class = "form-control" })*#
#Html.EditorFor(model => model.ProductID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EntryDate, "Entry Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EntryDate, new { htmlAttributes = new { #class = "form-control" } })
#*<input class="datefield" data-val="true" id="EntryDate" name="EntryDate" type="date" value=" " />*#
#Html.ValidationMessageFor(model => model.EntryDate, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExitDate, "Exit Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExitDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ExitDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<font color="#D3D1D1">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
</font>
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.Total, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Total, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Total, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink(" Back to List", "Index", null, new { #class = "glyphicon glyphicon-chevron-left" })
</div>
Basically what I need is, when I create the new row for tbl_NIR (e.g.: ID = 23 (autoincrement), blah blah), the value from the ID ("23") to be displayed in the partial view on the:
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
field. I think that maybe the "EdidorFor is the problem"!?
You cannot redirect to PartialView.
[HttpPost]
public ActionResult Add(BOL1.tbl_NIR nir)
{
if (ModelState.IsValid)
{
db.tbl_NIR.Add(nir);
db.SaveChanges();
Session["id"]=nir.ID;
return RedirectToAction("AddIO");
}
return View(nir);
}
C# -pass a new BOL1.tbl_I_O object.
[HttpGet]
public ActionResult AddIO()
{
return View(new BOL1.tbl_I_O());
}
HTML
Change
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
To
<input type="text" id="NirID" name="NirID" class="form-control" value="#Session["id"]"/>

how to upload image as part of a form with other fields in asp.net mvc5

I'm just trying record student information with an image profile. I want to upload the image as part of the form to application->Image directory and save the image name to the database.
This is my controller
public ActionResult Create([Bind(Include ="StudentId,StudentName,StudentLastName,StudentPhone,StudentAge,StudentEmail,photo")] Student student , HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
in my view
#using (Html.BeginForm("Create", "Students", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StudentName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentPhone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentPhone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentAge, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentAge, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentAge, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.photo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.photo, new { type = "file" })
#Html.ValidationMessageFor(model => model.photo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
but when i upload, it generates an error message
An exception of type 'System.NullReferenceException'
on this line
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName
please help me this issue please...
Try this one:
change it:
From
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName
To
file.SaveAs(HttpContext.Server.MapPath("~/Images/" + file.FileName))
System.NullReferenceException means that something is null at this reported line of code.
In this situation, it should be your HttpPostedFileBase file.
Try run the application in debug mode, and check again the name of your upload field, whether it's set as "file". MVC asp.net using Name attribute to define parameter.
In my case, I'm using a simple <input> to do the upload file and another <img> for displaying:
View:
<!--Displaying: You need some code for this-->
<img src="#ViewBag.ImagePath" alt="Message picture" style="width:100%;">
<!--Uploading-->
#using (Html.BeginForm("Create", "Students", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!-- Your other part of form -->
<!-- Uploading -->
<input type="file" name="file" />
}
Controller:
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// initial new path for upload file
var newSPath = Path.Combine(Server.MapPath("~/Images"), fileName);
// store file
file.SaveAs(newSPath);
Try this:-
public ActionResult Create([Bind(Include ="StudentId,StudentName,StudentLastName,StudentPhone,StudentAge,StudentEmail,photo")] Student student , HttpPostedFileBase photo)
{
if (ModelState.IsValid)
{
var fileName=Path.GetFileName(photo.FileName);
var path=Path.Combine(Server.MapPath("~/Images/") + fileName)
photo.SaveAs(path);
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}

Foreign Key Reference to IdentityUser Shows NULL Values (EF6/ASP.NET MVC 5)

I am trying to figure out why my model table's UserId column which references the primary key, "Id" of my AspNetUsers table (IdentityUser class in IdentityModel) is showing only NULL values when I 'Create()' an entry.
Here is the code for my two Create(), ActionResult methods in my controller class:
[Authorize]
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname");
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "ID,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense)
{
if (ModelState.IsValid)
{
expense.UserId = HttpContext.Current.User.Identity.Name;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId);
return View(expense);
}
Here is the code for my Create view:
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
DateTime today = DateTime.Today;
string formattedDate = today.ToString("MM/dd/yyyy");
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Expense</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #Value = user, #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateSubmitted, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateSubmitted, new { htmlAttributes = new { #Value = formattedDate, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateSubmitted, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExpenseDate, htmlAttributes: new { #Value = #formattedDate, #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExpenseDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ExpenseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Category, new SelectList(
new List<String>{
"Meals & Entertainment",
"Home Office",
"Travel",
"Phone",
"Auto - Mileage",
"Auto - Gas",
"Auto - Lease",
"Association Dues",
"Insurance Premium",
"Capital Assets",
"Trade Show & Promo",
"Pan Experience",
"Other"
}), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mileage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mileage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mileage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MileageRate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MileageRate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MileageRate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GrossAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GrossAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GrossAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TaxAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TaxAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TaxAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NetAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NetAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NetAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section scripts {
<script type="text/javascript">
var province = 'bc';
var grossAmount = document.getElementById('GrossAmount').value;
$(function () {
$('#ExpenseDate').datetimepicker({
defaultDate: '#formattedDate',
format: 'L',
showClose: true,
showClear: true,
toolbarPlacement: 'top'
});
});
$('#DateSubmitted').prop('readonly', true);
$('#Mileage').prop('disabled', true);
$('#MileageRate').prop('disabled', true);
$(function ()
{
$('#Category').on('change',function()
{
if ($(this).val() == 'Auto - Mileage')
{
$('#Mileage').prop('disabled', false);
$('#MileageRate').prop('disabled', false);
}
else
{
$('#Mileage').prop('disabled', true);
$('#MileageRate').prop('disabled', true);
}
}
)
})
</script>
}
If you would like to take a look at my model classes, you can go this post:
How To Restrict User Entries Only to that Sepcific User in EF 6/ASP.NET MVC 5
UPDATE:
Thanks to Steve Greene for putting me on the right track and for helping me to update my Create() method to this:
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname");
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "ExpenseId,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense)
{
if (ModelState.IsValid)
{
expense.UserId = System.Web.HttpContext.Current.User.Identity.Name;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId);
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
Response.Write(error);
}
}
Response.End();
return View(expense);
}
I don't get any major errors now, however, now ModelState.IsValid is returning False and the data I enter into Create.cshtml isn't being submitted.
I added a piece of code in the Create() method to catch the ModelState.Errors and it prints the error: System.Web.Mvc.ModelError.
I've also set a breakpoint before Create() and when I check the value of UserId, I get "null."
LAST UPDATE:
I've added a field for UserId to the Create.cshtml view and now I get the error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Expenses_dbo.AspNetUsers_ApplicationUser_Id". The conflict occurred in database "PacificPetExpenses", table "dbo.AspNetUsers", column 'Id'.
To fix this, I modified something in my controller (please see my answer below).
Thank you.
If you are not using the UserId in the view, just set it before you add:
if (ModelState.IsValid)
{
expense.UserId = HttpContext.Current.User.Identity.Name; // or whatever
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
Another common pattern is to add a hidden field for the UserId:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.UserId) <-- now it will post back
...
If you want to have a drop down list of users, do this:
[Authorize]
public ActionResult Create()
{
ViewBag.UserList = new SelectList(db.Users, "Id", "Fullname");
return View();
}
Then in your view add a drop down list of users:
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, Model.UserList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
Inside of the Create() method inside of my controller, I had the line:
expense.UserId = HttpContext.Current.User.Identity.Name;
I set up a break point and as breakpoint was on the line, it showed the correct UserId; however, after the line had executed, it showed the user's email address.
To fix this I tried changing the line above to:
expense.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
and expenses were both being submitted with no errors and displaying in the view where it was supposed to show the list of expenses submitted by the user!

Categories

Resources