I require a little bit of help with ASP.NET MVC data entry. Can anybody help me how would I save a new product that is automatically tied to a catalog? It is a requirement that the product can not be created without a catalog. But I can save the product only without the catalog, and this is what I got so far:
Entities:
The Model:
public partial class Product
{
public Product()
{
this.ProductsInCatalog = new HashSet<ProductsInCatalog>();
}
public int Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public virtual ICollection<ProductsInCatalog> ProductsInCatalog { get; set; }
}
public partial class Catalog
{
public Catalog()
{
this.ProductsInCatalog = new HashSet<ProductsInCatalog>();
}
public int Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public virtual ICollection<ProductsInCatalog> ProductsInCatalog { get; set; }
}
public partial class ProductsInCatalog
{
public int ProductId { get; set; }
public int CatalogId { get; set; }
public virtual Product Product { get; set; }
public virtual Catalog Catalog { get; set; }
}
The Controller:
public ActionResult Create()
{
CatalogManager catalogManager = new CatalogManager();
ViewBag.Catalogs = catalogManager.GetCatalogs();
return View();
}
[HttpPost]
[ActionName("Save")]
public ActionResult Save(EURIS.Entities.Product product)
{
if (ModelState.IsValid)
{
ProductManager productManager = new ProductManager();
productManager.SaveProduct(product);
}
return RedirectToAction("Index");
}
The EFCore Manager:
public class ProductManager
{
readonly LocalDbEntities _context = new LocalDbEntities();
public List<Product> GetProducts()
{
var products = (from item in _context.Product select item).ToList();
return products;
}
public Product GetProductByID(int productID)
{
return _context.Product.SingleOrDefault(e => e.Id == productID);
}
public bool SaveProduct(Product product)
{
try
{
_context.Product.Add(product);
_context.SaveChanges();
return true;
}
catch (System.Exception exe)
{
return false;
}
}
public bool DeleteProduct(int productID)
{
try
{
Product product = _context.Product.SingleOrDefault(e => e.Id == productID);
_context.Product.Remove(product);
_context.SaveChanges();
return true;
}
catch (System.Exception exe)
{
return false;
}
}
public bool UpdateProduct(Product product)
{
try
{
Product prodToUpdate = _context.Product.Where(p => p.Id == product.Id).FirstOrDefault();
if (prodToUpdate != null)
{
_context.Entry(prodToUpdate).CurrentValues.SetValues(product);
_context.SaveChanges();
return true;
}
return false;
}
catch (System.Exception exe)
{
return false;
}
}
}
The View:
#model EURIS.Entities.Product
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title</h2>
<p>
#Html.ActionLink("Back", "Index", "Product")
</p>
<table>
#using (Html.BeginForm("Save", "Product", FormMethod.Post))
{
<tr>
<td>Id</td>
<td>#Html.TextBoxFor(model => model.Id)</td>
<td>#Html.ValidationMessageFor(model => model.Id)</td>
</tr>
<tr>
<td>Code</td>
<td>#Html.TextBoxFor(model => model.Code)</td>
<td>#Html.ValidationMessageFor(model => model.Code)</td>
</tr>
<tr>
<td>Description</td>
<td>#Html.TextBoxFor(model => model.Description)</td>
<td>#Html.ValidationMessageFor(model => model.Description)</td>
</tr>
<tr>
<td>Catalog asoiation:</td>
<td>
<select id="ddlCatalog" onchange="onCatDdlChange">
#foreach (EURIS.Entities.Catalog cat in ViewBag.Catalogs)
{
<option value="#cat.Id">#cat.Code</option>
}
</select>
</td>
</tr>
<tr>
<td><button type="submit">Save</button></td>
</tr>
}
</table>
Related
I wanted to add the value of checkbox ids to many to many relation table between two tables Course-Student
i have 3 tables Course{ CourseID,CourseName }, Studdent{StudentID,StudentName} and CourseStudet{CourseID, StudentID}
Course table already have course{1.DataScience,2.English,3.Physics}
while Inserting Student i have shown course checkboxes with these options fetching list of these courses from database to show in view to user when he is about to register now i am confused how to insert into database?
public class CourseModel {
public List<Course> mycourse{ get; set; }
public string StudentName {get; set;}
}
EF generated Class
public partial class Course
{
public Course()
{
this.Student= new HashSet<Student>();
}
public int CourseID { get; set; }
public string CourseName { get; set; }
i have inserted this field to check for checked value
public bool Ischecked { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
public partial class Student
{
public Student()
{
this.Course= new HashSet<Course>();
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Course{ get; set; }
}
public ActionResult Index()
{
CourseModel coursemodel = new CourseModel();
using (Entities db = new Entities())
{
coursemodel.mycourse = db.Course.ToList<Course>();
return View(coursemodel);
}
}
[HttpPost]
public ActionResult Index(CourseModel course)
{
return View(course);
}
View
#using (Html.BeginForm("index", "Course", FormMethod.Post))
<input type="Text" name="StudentName" placeholder="Name" />
{
<table>
#for (int i = 0 ; i < Model.mycourse.Count; i++)
{
if (i % 3 == 0) {
#:<tr></tr>
}
<div>
#Html.CheckBoxFor(x => x.mycourse[i].Ischecked)
<label>#Model.mycourse[i].CourseName</label>
#Html.HiddenFor(x => x.mycourse[i].CourseID)
#Html.HiddenFor(x => x.mycourse[i].CourseName)
</div>
}
</table>
<input type="submit" value="Submit" />
}
i am getting checkbox id,name and which course is checked now how can i add student with including these values to relationship table CourseStudent ?
You have problems with your database design. Remove ischecked field.Remember while you are designing entities, you shouldn't put fields that are for view. It is like that I make Reports table from my each query.
correct your models
public partial class Course
{
public Course()
{
this.Student = new HashSet<Student>();
}
public int CourseID { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
public partial class Student
{
public Student()
{
this.Course = new HashSet<Course>();
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Course { get; set; }
}
Add viewmodels(You can use view models for showing custom data for your view)
You can read more
ViewModel
public class CourseViewModel
{
public Course course { get; set; }
public bool CheckBox { get; set; }
}
public class StudentCourseViewModel
{
public List<CourseViewModel> coursesVM { get; set; }
public Student student { get; set; }
}
Controller
public ActionResult index()
{
Entities db = new Entities();
List<CourseViewModel> courselist = new List<CourseViewModel>();
foreach (var item in db.Course.ToList())
{
courselist.Add(new CourseViewModel { course = item});
}
StudentCourceViewModel model = new StudentCourseViewModel(
{
student = new student(),
coursesVM = courselist }
};
return View(model);
}
[HttpPost]
public ActionResult Save(StudentCourseViewModel model)
{
Entities db = new Entities();
Student stdindb = db.Students.FirstorDefault(c => c.StudentName == model.student.StudentName);
if(stdindb == null)
{
stdindb = new student(){//your properties};
db.students.add(stdindb);
}
foreach (var item in model.coursesVM)
{
if (item.Ischecked)
{
stdindb.Course.Add(db.course.single(c=>c.CourseId == item.course.CourseId ));
}
}
db.SaveChanges();
return View();
}
View
#model SchoolCMS.Models.StudentCourseViewModel
#{
ViewBag.Title = "Select Course";
}
#using (Html.BeginForm("Save", "home", FormMethod.Post))
{
#Html.TextBoxFor(c=>c.student.StudentName)
<table>
#for (int i = 0; i < Model.coursesVM.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(c => c.coursesVM[i].Ischecked)
#Html.HiddenFor(c => c.coursesVM[i].course.CourseID)
</td>
<td>#Html.DisplayFor(c => c.coursesVM[i].course.CourseName)</td>
</tr>
}
</table>
<input type="submit" value="Submit" />
}
How to implicitly convert from one datatype in a class to another in asp.net mvc. How can I change my error in the controller?
models
public class ClsNews
{
public int Id { get; set; }
public string Description { get; set; }
}
public class NewsList
{
public int Id { get; set; }
public string description { get; set; }
public List<News> NewsLst { get; set; }
}
public partial class News
{
public int Id { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public string Description { get; set; }
public Nullable<bool> IsActive { get; set; }
}
view
<table class="table">
#{int i = 1;}
#for (var j = 0; j < Model.NewsLst.Count; j++)
{
<tr>
<td>
#Html.HiddenFor(m => Model.NewsLst[j].Id)
#Html.HiddenFor(m => Model.NewsLst[j].Description)
#Html.DisplayFor(m => Model.NewsLst[j].Description.Substring(0,20))
#Html.ActionLink("Read More", "NewsInnerPage", "News")
</td>
</tr>
i++;
}
</table>
this is my Controller
News news = await db.News.FindAsync(id);
NewsList nl = new NewsList();
nl.Id = id;
nl.description = (db.News.Where(h => h.Id == id)).Count() > 0 ?
(db.News.Where(h => h.Id == id)).First().Description : string.Empty;
var res = db.News.Where(s => s.Id == id).Select(t => new ClsNews
{
Id = t.Id,
Description = t.Description
}).ToList();
nl.NewsLst = res;
if (news == null)
{
return HttpNotFound();
}
return View(nl);
The error is generating in the controller where the value in variable res is attaching to the NewsLst. How can I correct my error?
I am new in mvc 5. I want to have a search using multiple fields. I have this code but I don't know how to pass the values from the view
View:
<input type="text" name="Id">
<input type="text" name="Price">
<input type="text" name="Name">
Product Class:
public class Product
{
public int Id { get; set; }
public int Price { get; set; }
public string Name { get; set; }
}
ProductSearchModel:
public class ProductSearchModel
{
public int? Id { get; set; }
public int? PriceFrom { get; set; }
public int? PriceTo { get; set; }
public string Name { get; set; }
}
ProductBusinessLogic:
public class ProductBusinessLogic
{
private YourDbContext Context;
public ProductBusinessLogic()
{
Context = new YourDbContext();
}
public IQueryable<Product> GetProducts(ProductSearchModel searchModel)
{
var result = Context.Products.AsQueryable();
if (searchModel != null)
{
if (searchModel.Id.HasValue)
result = result.Where(x => x.Id == searchModel.Id);
if (!string.IsNullOrEmpty(searchModel.Name))
result = result.Where(x => x.Name.Contains(searchModel.Name));
if (searchModel.PriceFrom.HasValue)
result = result.Where(x => x.Price >= searchModel.PriceFrom);
if (searchModel.PriceTo.HasValue)
result = result.Where(x => x.Price <= searchModel.PriceTo);
}
return result;
}
}
Product Controller:
public ActionResult Index(ProductSearchModel searchModel)
{
var business = new ProductBusinessLogic();
var model = business.GetProducts(searchModel);
return View(model);
}
I have a component that have a list of subcomponents:
public class Componente
{
public virtual int ComponentId { get; set; }
public virtual string NameComp { get; set; }
public virtual List<Subcomponent> Subcomponents { get; set; }
}
public class Subcomponent
{
public virtual int SubcomponentId { get; set; }
public virtual int ParentId { get; set; }
public virtual string NameSub { get; set; }
public virtual Component CompSub { get; set; }
public virtual List<Subcomponent> Children { get; set; }
}
Then i have a view that shows the components, their subcomponents and in the future the subsubcomponents and so on.
<table>
...
if (item.Subcomponents.Count != 0)
{
foreach (var x in item.Subcomponents)
{
<tr>
<td>
#Html.DisplayFor(modelItem => x.NameSub)
</td>
<td>
#Html.ActionLink("Create Subcomponent", "CreateMoreSubcomponents", "Subcomponent", new { id = x.SubcomponentId }, null)
</td>
</tr>
}
}
}
</table>
And the create method:
public ActionResult CreateMoreSubcomponents(int id)
{
var x = db.Subcomponents.FirstOrDefault(e => e.SubcomponentId == id);
if (x == null)
{
return HttpNotFound();
}
var subcomponent = new Subcomponent()
{
ParentId = x.SubcomponentId
};
return View("CreateMoreSubcomponents", subcomponent);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMoreSubcomponents(Subcomponent subcomponent)
{
if (ModelState.IsValid)
{
db.Subcomponents.Add(subcomponent);
db.SaveChanges();
...
}
The goal is to have subsubcomponents, subsubsubcomponents and so on. But the code that i show here is not working, it gives an error in the db.SaveChanges(); because it asks for the componentId but i don't know what do i have to change. What do i need to change or do? Thanks
I have a Menusettings pages which displays all the menuname from the database(Menutable).I want to save all the details into MenuRole table.For that I think I have to iterate over each menuitem and store the details in the MenuRole table(Is it the correct method?).But the problem is I am getting MenuList as null.So I couldnot iterate over the menulist .Also I am not sure how can i bind the checkbox value to the MenuRole table.
The view is
Model is
public class MenuRoleVM
{
public int? RoleId { get; set; }
public SelectList RoleList { get; set; }
public MenuRole MenuRole { get; set; }
public IEnumerable<Menu> MenuList { get; set; }
}
public partial class MenuRole
{
public int Id { get; set; }
public Nullable<int> MenuID { get; set; }
public Nullable<int> RoleID { get; set; }
public Nullable<System.DateTime> TransactionTime { get; set; }
public bool CanAdd { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool CanView { get; set; }
public virtual Menu Menu { get; set; }
public virtual Role Role { get; set; }
}
public partial class Menu
{
public Menu()
{
this.MenuRoles = new HashSet<MenuRole>();
}
public int Id { get; set; }
public string MenuName { get; set; }
public string NavigateUrl { get; set; }
public Nullable<int> ParentID { get; set; }
public virtual ICollection<MenuRole> MenuRoles { get; set; }
}
Controller for binding the View
public ActionResult Add()
{
var _menuRoleVM = new MenuRoleVM
{
RoleList = new SelectList(_db.Roles.ToList(), "Id", "RoleName"),
MenuList = _db.Menus.Where(m => m.NavigateUrl != "#"),
MenuRole = new MenuRole()
};
return View(_menuRoleVM);
}
HTML Markup of View
#model SMS.Models.ViewModel.MenuRoleVM
#foreach (var item in Model.MenuList.Select((x, i) => new { Data = x, Index = i }))
{
<tr>
<td>
<input type="checkbox" class="minimal checkAll" />
</td>
<td>#item.Data.MenuName</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanAdd, new { #class = "minimal single" })
</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanEdit, new { #class = "minimal single" })
</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanDelete, new { #class = "minimal single" })
</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanView, new { #class = "minimal single" })
</td>
</tr>
}
Any help is highly appreciated?
You need view models that represent what you want to display/edit
public class MenuVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool CanAdd { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool CanView { get; set; }
}
public class MenuRoleVM
{
public int? RoleId { get; set; }
public SelectList RoleList { get; set; }
public List<MenuVM> MenuList { get; set; }
}
and in the view
#model MenuRoleVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.RoleId, Model.RoleList)
for(int i = 0; i < Model.MenuList.Count; i++)
{
#Html.HiddenFor(m => m.MenuList[i].ID)
#Html.DisplayFor(m => m.MenuList[i].Name)
#Html.CheckBoxFor(m => m.MenuList[i].CanAdd)
#Html.CheckBoxFor(m => m.MenuList[i].CanEdit)
....
}
<input type="submit" ... />
}