How to use mutiple models for one dbset - asp.net

NET MVC expetrts!
I'm new in asp.NET MVC 4, so I got a simple problem not to know how to solve!
so this is my NotActivatedUsers model :
public class NotActivatedUser
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DefaultValue(false)]
public bool isActive { get; set; }
[Required, DataType(DataType.EmailAddress)]
public string email { get; set; }
[Required]
public string activeCode { get; set; }
public DateTime createDate { get; set; }
}
and here is my SignUp model :
public class SignUpModel
{
[Key]
public int id { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email!")]
public string email { get; set; }
}
and this in my dbset:
public class Context : DbContext
{
public DbSet<NotActivatedUser> notActivatedUser { get; set; }
}
My problem is " How to use my SignUp model to insert into NotActivatedUsers Dbset?
I tried this :
public class AccountController : Controller
{
private Context db = new Context();
[HttpPost]
[AllowAnonymous]
public ActionResult SignUp(SignUpModel signUpModel)
{
if (ModelState.IsValid)
{
db.notActivatedUser.Add(signUpModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(signUpModel);
}
[AllowAnonymous]
public ActionResult SignUp()
{
return View();
}
}

Related

ASP.NET Core 3.1 ModelState validation fail for nullable

The issue I am having, is that if you provide a null value for an item, that is nullable, the ModelState.IsValid flags a validation error saying "The value ParentID is not valid for ParentID."
I want [int?] to allow null.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("common/menu-setting/add")]
public IActionResult AddMenuSetting(Menu model)
{
if (!ModelState.IsValid)
{
ViewData["ParentMenus"] = _commonRepository.GetParentMenus();
return View(model);
}
var returnValue = _commonRepository.AddMenu(model);
if (!returnValue)
{
return RedirectToAction("AddMenuSetting");
}
return RedirectToAction("MenuSetting");
}
Model:
public class Menu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public int? ParentID { get; set; }
public string ParentMenuName { get; set; }
public int SortGroup { get; set; }
public int Sort { get; set; }
}

How to create a drop-down in asp.net core MVC from another Model with validation?

Model Class.cs
public class Class
{
public int ClassId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Class Name")]
public string ClassName { get; set; }
}
Model Subject.cs
public class Subject
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
public string SubjectName { get; set; }
public int ClassId { get; set; }
public Class Class { get; set; }
}
ViewModel CreateSubjectViewModel.cs
public class CreateSubjectViewModel
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Subject Name")]
public string SubjectName { get; set; }
public int ClassId { get; set; }
public int ClassesId { get; set; }
public virtual List<Class> Classes { get; set; }
}
Controller Code
[HttpGet]
public IActionResult CreateSubject()
{
List<Class> classList = _context.Classes.ToList();
ViewData["classList"] = classList.Select(x => new SelectListItem { Value = x.EncryptedId, Text = x.ClassName });
return View();
}
[HttpPost]
public IActionResult CreateSubject(CreateSubjectViewModel model)
{
if (ModelState.IsValid)
{
Subject newSubject = new Subject
{
//SubjectName = model.SubjectName,
//here code for store data in subject table
};
_cdsRepository.AddSubject(newSubject);
return RedirectToAction("ListClasses", "UDP");
}
return View(model);
}
How can I get data from Class.cs and show in drop-down with proper validation of drop-down on button click.
If everything is OK, then store data in Subject.cs with Class Id value.

Delete in cascade

I'm new to asp.net and mvc.
I have a class AsyApp
public class AsyApp
{
[Key]
public int AsyAppId { get; set; }
[DisplayName("Nom")]
public string Name { get; set; }
public virtual ICollection<Scene> Scenes { get; set; }
}
It has a collection of scenes
public class Scene
{
[Key]
[Required]
public int SceneId { get; set; }
[ForeignKey("AsyApp")]
public int AsyAppId { get; set; }
[Required]
public virtual AsyApp AsyApp { get; set; }
[ForeignKey("Name")]
public int NameId { get; set; }
[DisplayName("Nom")]
public virtual Translation Name { get; set; }
public int Order { get; set; }
}
And the Scene has a property Name from a class Translation
public class Translation
{
[Key]
[Required]
public int TranslationId { get; set; }
public string Fr { get; set; }
public string En { get; set; }
}
Here is my issue.
I will use the class Translation to handle language for every single string in my application. I could be in any other classes
I would like that when I delete an application, it delete the appropriate scenes and localisations
Here is my code for deleting an app
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AsyApp asyApp = db.AsyApps.Find(id);
if (asyApp == null)
{
return HttpNotFound();
}
db.AsyApps.Remove(asyApp);
db.SaveChanges();
return RedirectToAction("Index");
}
The scenes seams to be deleted automaticaly but not the localisations associated with them...
Hope you can help me
Thanks a lot
look at this link:
https://msdn.microsoft.com/en-us/data/jj591620.aspx#CascadeDelete
you can enable cascade delete using Fluent API.

How to make single view using viewmodel in asp.net mvc 4?

I have different models Image,Page & PageCategories
public class Image
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
}
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public virtual PageCategory PageCategory { get; set; }
}
public class PageCategory
{
public int PageCategoryId { get; set; }
public string CategoryName { get; set;
public virtual ICollection<Page> Pages { get; set; }
}
DBContext Class is
class DemoContext:DbContext
{
public DbSet<PageCategory> PageCategories { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
I am wondering how to get all the model data to the home page using ViewModel.
For Ex.:
How to get image list and Page list in home page from multiple models?
You may want something like this :
viewModel :
//Create a viewModel with all the properties that you need
public class ViewModel
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public string CategoryName { get; set; }
}
Controller :
...
using (DemoContext db = new DemoContext()){
List<ImagePageViewModel> viewData = (from p in db.Page
join pc from db.PageCategory on p.PageCategoryId equals pc.PageCategoryId
select new ViewModel(){
PageTitle=p.PageTitle,
CategoryName = pc.CategoryName
//... set every property you want
})
}
return View(viewData );
note: I didn't add Image to the query because there is no explicit relation
between Image and the others table so i let you do it.
Create another class and define all above three into it. like below
public class MyView
{
public List<Image> Images { get; set; }
public List<Page> Pages { get; set; }
public List<PageCategory> PageCategories { get; set; }
}
Controller Action:-
public ActionResult Index()
{
MyView myView = // Get it using your logic
return View(myView);
}
finally got my answer:
public class ViewModelDemo
{
public IEnumerable<Image> images { get; set; }
public IEnumerable<Pages> pages { get; set; }
public IEnumerable<PageCategory> pagecategories { get; set; }
}
Then in HomeController
private DemoContext db=new DemoContext();
public ActionResult Index()
{
ViewModelDemo vm = new ViewModelDemo();
vm.images = db.Images.ToList();
vm.pages=db.Pagess.ToList();
vm.pagecategories=db.PageCategories.ToList();
return View(vm);
}

ASP.NET MVC5 custom json model binder with html content

I used the FromJsonAttribute (created by Steve Sanderson), it's quite great, but sadly it doesn't pay attention to the AllowHtml attribute. I have the following model:
public class HKNewsPaperViewModel
{
public int Id { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string RPublisher { get; set; }
public string REditor { get; set; }
public string Title { get; set; }
public bool IsDraft { get; set; }
public bool IsNew { get; set; }
public List<HKNewsItemViewModel> NewsItems { get; set; }
public HKNewsPaperViewModel()
{
NewsItems = new List<HKNewsItemViewModel>();
}
}
public class HKNewsItemViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Link { get; set; }
[AllowHtml]
public string Body { get; set; }
}
In my controller I receive data this way:
[HttpPost]
public ActionResult New([FromJson] HKNewsPaperViewModel model)
{
return View();
}
FromJson attribute looks like this:
public class FromJsonAttribute : CustomModelBinderAttribute
{
private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
private class JsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return serializer.Deserialize(stringified, bindingContext.ModelType);
}
}
}
My problem is that I can't pass html content where the AllowHtml attribute is there. Thanks a lot!

Resources