I have a question about how to get data from a database.
This is my code so far:
public class TabController : Controller
{
private TestEntities db = new TestEntities();
public ActionResult Index()
{
var model = GetTab();
return View(model);
}
private IEnumerable<MN_REITER> GetReiter()
{
var reiters = Enumerable.Range(0,5).Select(
i => new MN_REITER
{
TabId = i,
TabDescription = "Tab "+i
//REITER_LABEL = "Label" + i
});
return reiters;
}
Like answer a have a Tab0 to Tab5, but I want a get the information from database.
Edit:
View.cshtml
#model IEnumerable >rcMDM.Data.MN_REITER>
(Html.Kendo().TabStrip()
.Name("reiterTab")
.BindTo(Model, (item, reiter)=>
{
item.Text = reiter.REITER_BEZEICHNUNG;
// item.Template.Html = reiter.REITER_LABEL;
})
and the model
public partial class MN_REITER
{
public decimal REITERID { get; set; }
public string REITER_BEZEICHNUNG { get; set; }
public string REITER_LABEL { get; set; }
}
}
Related
I'm new to Entity Framework Core and learning.
I have a question: I have three tables with many-to-many relations (Product, ProductCategory, Categories). Everything works fine, I can update, delete and add database.
But I couldn't add Product data to related tables. It just inserts into the Product table, but I want to add Id data to ProductCategories.
Thank you for helping me here.
This is my code:
Generic repository
public class EfCoreGenericRepository<TEntity, TContext> : IRepository<TEntity>
where TEntity : class
where TContext : DbContext, new()
{
public virtual void Create(TEntity entity)
{
using (var context = new TContext())
{
context.Set<TEntity>().Add(entity);
context.SaveChanges();
}
}
public void Delete(TEntity entity)
{
using (var context = new TContext())
{
context.Set<TEntity>().Remove(entity);
context.SaveChanges();
}
}
public List<TEntity> GetAll()
{
using (var context = new TContext())
{
return context.Set<TEntity>().ToList();
}
}
public TEntity GetById(int id)
{
using (var context = new TContext())
{
return context.Set<TEntity>().Find(id);
}
}
public virtual void Update(TEntity entity)
{
using (var context = new TContext())
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}
}
}
ProductRepository
public class EfCoreProductRepository : EfCoreGenericRepository<Product, FoodContext>, IProductRepository
{
public Product GetByIdWithCategories(int id)
{
using (var context = new FoodContext())
{
return context.Products
.Where(p => p.ProductId == id)
.Include(p => p.ProductCategories)
.ThenInclude(pc => pc.Category)
.FirstOrDefault();
}
}
public List<Product> GetProductsByCategory(string name)
{
using (var context = new FoodContext())
{
var products = context.Products.AsQueryable();
if (!string.IsNullOrEmpty(name))
{
products = products.Include(i => i.ProductCategories)
.ThenInclude(i => i.Category)
.Where(i => i.ProductCategories.Any(a => a.Category.Name.ToLower() == name.ToLower()));
}
return products.ToList();
}
}
public void Update(Product entity, int[] categoryIds)
{
using (var context = new FoodContext())
{
var product = context.Products
.Include(i => i.ProductCategories)
.FirstOrDefault(i => i.ProductId == entity.ProductId);
if (product != null)
{
product.Name = entity.Name;
product.Price = entity.Price;
product.ImageUrl = entity.ImageUrl;
product.ProductCategories = categoryIds.Select(catid => new ProductCategory() {
ProductId = entity.ProductId,
CategoryId = catid
}).ToList();
}
context.SaveChanges();
}
}
// I may override Create code here.
}
MVC Post method
[HttpPost]
public async Task<IActionResult> CreateProduct(ProductModel model, IFormFile file)
{
if (ModelState.IsValid)
{
if (file != null)
{
var extension = Path.GetExtension(file.FileName);
var randomName = string.Format($"{DateTime.Now.Ticks}{extension}");
model.ImageUrl = randomName;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\img\\Products", randomName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
var entity = new Product()
{
Name = model.Name,
Price = model.Price,
ImageUrl = model.ImageUrl,
CategoryId = model.CategoryId
};
if (_productService.Create(entity))
{
TempData.Put("message", new AlertMessage
{
Title = $"{entity.Name} named product added successfully",
Message = $"{entity.Name} named product added successfully",
AlertType = "alert-success"
});
return RedirectToAction("ProductList");
};
TempData.Put("message", new AlertMessage
{
Title = _productService.ErrorMessage,
Message = _productService.ErrorMessage,
});
}
ViewBag.Categories = _categoryService.GetAll();
return View(model);
}
You can ask for more code if you need to see it. Thanks for now!
Edit ---> Entity Classes
Category.cs
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public List<ProductCategory> ProductCategories{get; set;}
}
Product.cs
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public double? Price { get; set; }
public bool IsApproved { get; set; }
public int? CategoryId { get; set; }
public string ImageUrl { get; set; }
public List<ProductCategory> ProductCategories{get; set;}
}
ProductCategories.cs
public class ProductCategory
{
public int CategoryId { get; set; }
public Category Category { get; set; }
public int ProductId { get; set; }
public Product Product{get; set;}
}
Thanks to Pirate. I solved problem. I'm new in efcore but i was aware of many to many relationship unnecessary. I had done for many products with many categories but I changed my mind later. Maybe I can use it for next codes.
public override void Create(Product entity)
{
base.Create(entity);
using (var context = new FoodContext())
{
var product = context.Products
.Where(i=>i.ProductId==entity.ProductId)
.Include(i=>i.ProductCategories).FirstOrDefault();
product.ProductCategories.Add(new ProductCategory(){
ProductId=entity.ProductId,
CategoryId=(int)entity.CategoryId
});
context.SaveChanges();
}
}
Note: I don't know how true using double using-code-block
I am new to mvc so here is my problem I have created a jquery-datatble with a action link named "detalles". When a user clicks on it I what to be able to see the details of the item selected in the jquery-datatble. Once the user has clicked on it. It opens a new tab that has a form with fields and also an other jquery-datatble. Basicly my idea would be to only have one return in the controler that return the view and th json.
Here is my Action result for i "detalles"
public ActionResult Detalles(int? id)
{
proveedorContext proveedorContext = new proveedorContext();
if (id == null)
{
}
proveedorModel proveedor = proveedorContext.GetAllProveedor().Find(obj => obj.proveedor_id == id);
//When i am here my model is not empty
loadProveedorContactoTable(proveedor);
if (proveedor == null)
{
}
return View(proveedor);
}
But unfortunately after words my program calls "loadProveedorContactoTable" again and then my model is completely null
public ActionResult loadProveedorContactoTable(proveedorModel model)
{
try
{
var proveedorsContactoData = model.contactos.OrderBy(a => a.nombre_contacto).ToList();
return Json(new { data = proveedorsContactoData }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
Here is my proveedorModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace erp_colombia.Models
{
public class proveedorModel
{
public int proveedor_id { get; set; }
public string nombre { get; set; }
public string direccion { get; set; }
public string codigo_postal { get; set; }
public string cuidad { get; set; }
public string pais { get; set; }
public string pagina_internet { get; set; }
public int compras_cantidad { get; set; }
public int componente_cantidad { get; set; }
public int eliminado { get; set; }
public List<ContactoModel> contactos { get; set; }
}
}
And here is how I read the data for contactos and proveedor()
public List<proveedorModel> GetAllProveedor()
{
List<proveedorModel> list = new List<proveedorModel>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM erp_proveedores",conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new proveedorModel()
{
proveedor_id = int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))),
nombre = reader.GetString(reader.GetOrdinal("nombre")),
direccion = reader.GetString(reader.GetOrdinal("direccion")),
codigo_postal = reader.GetString(reader.GetOrdinal("codigo_postal")),
cuidad = reader.GetString(reader.GetOrdinal("cuidad")),
pais = reader.GetString(reader.GetOrdinal("pais")),
pagina_internet = reader.GetString(reader.GetOrdinal("pagina_internet")),
eliminado = int.Parse(reader.GetString(reader.GetOrdinal("eliminado"))),
contactos = new proveedorContactoContext().GetAllProveedorContactos(int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))))
});
}
}
return list;
}
}
What can I do to fix this problem thank you for your help. I am thinking about making one return that would return the json and the view how could I so thar
I'm trying to include a search functionality in a ASP.NET Web Application using a search textbox. I have a controller (HomeController) which include an Index (list all data) and a Search (based on user input) Action Method but I'm having trouble writing the code/query for the Search Action Method. Any help would be appreciated. Thanks
//textbox from the View
#using (Html.BeginForm("Search", "Home"))
{
#Html.Editor("SearchBox")
<input type="submit" value="Search" />
}
//The model
public class EventViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime StartDateTime { get; set; }
public TimeSpan? Duration { get; set; }
public string Author { get; set; }
public string Location { get; set; }
public static Expression<Func<Event, EventViewModel>> ViewModel
{
get
{
return e => new EventViewModel()
{
Id = e.Id,
Title = e.Title,
StartDateTime = e.StartDateTime,
Duration = e.Duration,
Location = e.Location,
Author = e.Author.FullName
};
}
}
}
public class UpcomingPassedEventsViewModel
{
public IEnumerable<EventViewModel> UpcomingEvents { get; set; }
public IEnumerable<EventViewModel> PassedEvents { get; set; }
}
//controller
public class HomeController : BaseController
{
public ActionResult Index()
{
var events = this.db.Events
.OrderBy(e => e.StartDateTime)
.Where(e => e.IsPublic)
.Select(EventViewModel.ViewModel);
var upcomingEvents = events.Where(e => e.StartDateTime > DateTime.Now);
var passedEvents = events.Where(e => e.StartDateTime <= DateTime.Now);
return View(new UpcomingPassedEventsViewModel()
{
UpcomingEvents = upcomingEvents,
PassedEvents = passedEvents
});
}
public ActionResult Search(string SearchBox)
{
}
Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:
public JsonResult GetInfor()
{
List<AdminPurpose> all = new List<AdminPurpose>();;
using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {
var datas = (from a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id
select new {
a,
b.PurPose1
});
if(datas != null) {
foreach (var i in datas)
{
AdminPurpose con = i.a ;
con.PurPose1 = i.PurPose1;
all.Add(con);
}
}
}
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Model class one to many relation here it's using
[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
public string PurPose1 { get; set; }
}
public class DuaMetaData
{
public string Dua_Name { get; set; }
public string Arabic_Word { get; set; }
public string Translation_English { get; set; }
public string Source { get; set; }
[Display(Name = "Purpose")]
public int PurposeId { get; set; }
}
Hi Guys/Girls Im super new to asp.net mvc and Im trying to convert my date to a readable format. Currently it looks like this.
/Date(1444892163827)/
My Model
public class Movie
{
internal string title;
internal DateTime releasedate;
internal string genre;
public int ID { get; set; }
[Required]
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
[Required]
public string Genre { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
My Controller
public JsonResult getAll()
{
using (MovieDBContext dataContext = new MovieDBContext())
{
var movieList = dataContext.Movies.ToList();
return Json(movieList, JsonRequestBehavior.AllowGet);
}
}
public JsonResult getMovieByNo(string MovNo)
{
using (MovieDBContext dataContext = new MovieDBContext())
{
int no = Convert.ToInt32(MovNo);
var movieList = dataContext.Movies.Find(no);
return Json(movieList, JsonRequestBehavior.AllowGet);
}
}
Any help would really be appreciated !
You need create CustomJsonResult in MVC where you use for example JSON.Net with IsoDateTimeConverter or you should change your project MVC to WebAPI if you return only JSON.
Create class from this https://stackoverflow.com/a/9302054/4599089 (Approach 2) and then use this in controller:
public JsonResult getAll()
{
using (MovieDBContext dataContext = new MovieDBContext())
{
var movieList = dataContext.Movies.ToList();
return new CustomJsonResult(){Data = movieList};
}
}
public JsonResult getMovieByNo(string MovNo)
{
using (MovieDBContext dataContext = new MovieDBContext())
{
int no = Convert.ToInt32(MovNo);
var movieList = dataContext.Movies.Find(no);
return new CustomJsonResult(){Data = movieList};
}
}