Finding value of object id - c#

I have created an action result that allows restuarant to save their menu to a database. My issue is that I need to use the menuID for another controller but when I run the code the the variable menuID is always 0 instead of the value that was just added to the database.
Any help would be grateful.
Create Menu Action Result
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MenuViewModel model)
{
if (ModelState.IsValid)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
using (var objCtx = new ApplicationDbContext())
{
var currentrestaurant = (from r in objCtx.Restaurants
where r.UserID == currentUser.Id
select r).First<Restaurant>().id;
var menu = new Menu() { Name = model.Name, Restaurantid = currentrestaurant };
var menuID = menu.Id;
db.Menus.Add(menu);
db.SaveChanges();
return RedirectToAction("Create", "Meal", new { MenudID = menuID});
}
}
return View();
}

Most likely the ID is generated in database. If this is the case menu.Id will have the actual value after you save the object to DB, not before. So you need to reorder your code:
var menu = new Menu() { Name = model.Name, Restaurantid = currentrestaurant };
db.Menus.Add(menu);
db.SaveChanges();
return RedirectToAction("Create", "Meal", new { MenudID = menu.Id});
Side note. Make sure parameter in the last line is spelled correctly - shouldn't it be MenuID instead of MenudID?

Related

Incorrect Models passed to View MVC C# error

Can anyone help me correct the issue im having creating a view in MVC. Normally i just use Add/View and it scaffolds a view for me based upon my created method. The only problem is that this time i am creating a method to pass to view and i keep getting this error message
The model item passed into the dictionary is of type 'UserJob',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[UserJob]'.
The Methods i have written are the following...
public ActionResult AddJob(string userCode)
{
var jobs = jobsClient.GetAlljobs();
var alljobsCode = (from s in jobs select s.jobCode).ToList();
var usersJobs = (from s in db.UserJobs
where s.userCode == userCode
select s.jobCode).ToList();
var jobsNeeded = alljobsCode.Except(usersJobs);
List<UserJobsDTO> list = listBuilder(jobs, jobsNeeded);
ViewBag.jobCode = new SelectList(list, "jobCode", "jobDescription");
var model = new UserJob { userCode = userCode };
return View("AddJob", model);
}
private List<UserJobsDTO> listBuilder(
jobsService.jobsDTO[] jobs, IEnumerable<string> jobsNeeded)
{
List<UserJobsDTO> d = new List<UserJobsDTO>();
var f = jobsNeeded.ToArray();
var a = jobs.ToArray();
for (int i = 0; i < f.Length; i++)
{
d.Add(new UserJobsDTO()
{
jobCode = f.ElementAt(i),
description = a[i].jobDescription
});
}
return d;
}
When im debugging all of the required data is being passed to all the correct variable i am declaring, but the view just isnt playing ball. I was under the impression that scaffolding would automatically generate a useable View for me in Razor?? But this method just want play. Can anyone point me in the right direction??
Corrected version
public ActionResult AddJob(string userCode)
{
var jobs = jobsClient.GetAlljobs();
var alljobsCode = (from s in jobs select s.jobCode).ToList();
var usersJobs = (from s in db.UserJobs
where s.userCode == userCode
select s.jobCode).ToList();
var jobsNeeded = alljobsCode.Except(usersJobs);
List<UserJobsDTO> list = listBuilder(jobs, jobsNeeded);
ViewBag.jobCode = new SelectList(list, "jobCode", "jobDescription");
// var model = new UserJob { userCode = userCode };
return View("AddJob", usersJobs );
}
you will need to pass ienumarable here not an object type.
Update
#model IEnumerable<UserJobs>
foreach(var item in Model){
<span>#item.JobId</span>
<span>#item.JobName</span>
}

How to save drop down list item to database, selected from another table and save to another table

I have been strugling with this for some time now, I have a registration page with 3 tables (faculty(with dropdown list items(Id,Name)), staff and students)
both students and staff tables have text fields(name,surname,contactnr, email_adress etc)
and a dropdown list to select which Faculty the staff/student is under.
i used a database table to put in my dropdown list items for selecting when the program loads.
when i run my program the dropdown items are showing perfectly but now i want to save the selected dropdown item to my staff table or students table depending which user is registering.
I did this code below, but its giving me an error on registration that says that
"An exception of type 'System.InvalidOperationException' occurred in
System.Web.Mvc.dll but was not handled in user code,There is no
ViewData item of type 'IEnumerable' that has the key
'Faculty'."
and it undelines my dropdown code. anyone who can suggest how to solve this please. Thank you in advance
Controller
public ActionResult Register()
{
DataClasses1DataContext db = new DataClasses1DataContext();
ViewBag.Faculty = new SelectList(db.Faculties, "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(StudentsModel U)
{
if (ModelState.IsValid)
{
try
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
{
User newone = new User();
newone.EmailID = U.EmailID;
newone.Name = U.Name;
newone.Surname = U.Surname;
newone.Contact_Nr = U.Contact_Nr;
newone.Department = U.Department;
newone.Access_Num = U.Access_Num;
newone.Faculty = U.Name;
var count = db.Users.Count(a => a.EmailID == U.EmailID);
if (count == 0)
{
db.Users.InsertOnSubmit(newone);
db.SubmitChanges();
ViewData["Message"] = "Successful Registration";
ModelState.Clear();
}
else
{
// something to do if user exist...
ViewData["Message"] = "User Exists, Register with a new Email Address";
ModelState.Clear();
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(U);
}
}
View
#Html.DropDownList("Faculty", null, htmlAttributes: new { #class = "form-control" })

Cannot implicitly convert type 'System.Linq.IQueryable?

here is my code which is giving me above error
public ActionResult Edit(int id = 0)
{
KBS_Virtual_TrainingEntities db = new KBS_Virtual_TrainingEntities();
UsersContext ctx = new UsersContext();
UserProfile model = ctx.UserProfiles.Find(id);
List<CourseSubscription> user_Course_subscriptions = new List<CourseSubscription>();
foreach (UserSubscription sub in db.UserSubscriptions)
{
if (sub.ID == id)
{
user_Course_subscriptions.Add(sub.CourseSubscription);
}
}
List<CourseSubscription> not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions);
var coursesList = from courses in not_subscribe
select new SelectListItem
{
Text = courses.Course.Name,
Value = courses.Course.ID
.ToString()
};
var CoursesTYPE = from CourseTypes in db.CourseTypes.ToList()
select new SelectListItem
{
Text = CourseTypes.Name,
Value = CourseTypes.ID
.ToString()
};
ViewBag.CourseID = coursesList;
ViewBag.type = CoursesTYPE;
return View(model);
}
I am trying to find Course Subscription that are not subscribe by the current user by using the above code but its not working?
You're missing ToList on the results from your Except function. Do a ToList like so:
List<CourseSubscription> not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions).ToList();
Or since in your code you're not doing anything that needs a list, simply var it or assign the correct type to it such as IQueryable<CourseSubscription> to it.
var not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions);

Insert data using Entity Framework model

I'm trying to insert some data in my database using Entity Framework model, but for some unknown reasons to me, it does nothing.
Am I missing something here?
using (var context = new DatabaseEntities())
{
var t = new test
{
ID = Guid.NewGuid(),
name = "blah",
};
context.AddTotest(t);
context.SaveChanges();
}
It should be:
context.TableName.Add(TableEntityInstance);
For versions of entity framework before 6, it was:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName: the name of the table in the database.
TableEntityInstance: an instance of the table entity class.
If your table is Orders, then:
Order order = new Order();
context.Orders.Add(order);
For example:
var id = Guid.NewGuid();
// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );
db.SaveChanges();
}
Here is an example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();
var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();
if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;
this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();
screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;
this.ObjectContext.Screenshots.Add(screenshot);
this.ObjectContext.SaveChanges();
}
}
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
[HttpPost] // it use when you write logic on button click event
public ActionResult DemoInsert(EmployeeModel emp)
{
Employee emptbl = new Employee(); // make object of table
emptbl.EmpName = emp.EmpName;
emptbl.EmpAddress = emp.EmpAddress; // add if any field you want insert
dbc.Employees.Add(emptbl); // pass the table object
dbc.SaveChanges();
return View();
}

How can I return an ActionResult?

I have an ActionResult that returns a View with a grid that show notes from a database. On the same page there is a button to call CreateNote, which returns a PartialView where I can add new notes. This all works, but after adding the new note I want the view to go back to the TabNotes showing the grid.
I tried using
return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
but this goes to the wrong page. So instead I want to return the TabNotes ActionResult. Is this possible?
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
{
if (cmd == "Save")
{
Model.meta.message = "Note saved";
//standard user = 1, needs to be changed to variable
test.Database.User User = UserRepository.GetUser(1);
Entity entity = NotesRepository.GetEntity("Phrase");
NotesRepository.StoreNote(Model.subject, Model.text, User, entity, itemId);
return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
}
Model.meta.modelname = "CreateNote";
Model.meta.JsViewModelType = "EditNoteModel";
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId});
return PartialView("CreateNotePartial",Model);
}
'
public ActionResult TabNotes([ModelBinder(typeof(Models.JsonModelBinder))]
TabNotesModel Model, string cmd)
{
Entity entity = NotesRepository.GetEntity(Model.meta.entity);
if (Model.meta.id.HasValue)
{
Model.meta.modelname = "TN" + Model.meta.entity + Model.meta.id.Value.ToString();
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId", Model.meta.id.Value);
Entity noteEntity = NotesRepository.GetEntity("Note");
var grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
grid.buttons.Clear();
grid.title = "";
Model.Grid = grid;
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
You should redirect to the action:
return RedirectToAction("TabNotes");

Categories