EditorForModel/DisplayForModel Rendering Nothing - asp.net

I have a very basic problem in MVC 4. I am trying to use the "EditorForModel" to render a simple form, but the HTML is always blank (no Exception, nothing).
ViewModel:
public class ProjectViewModel {
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public string Client { get; set; }
public bool Secured { get; set; }
public DateTime StartDate { get; set; }
}
Controller Action:
[HttpGet]
public ActionResult New() {
return View(new ProjectViewModel());
}
View:
#model BuMan.ViewModels.ProjectViewModel
#{ Html.EditorForModel();}
I am obviously missing something very obvious, but shouldn't that render some default inputs for each property?!

You should remove curlybraces around Html.EditorForModel.
Your view should be
#model BuMan.ViewModels.ProjectViewModel
#Html.EditorForModel()

Related

How to fix ‘Cannot create a DbSet for 'DM_NCC_ThueSuat' because this type is not included in the model for the context’ error in C# ASP.NET

I have a code block regards get a list like that in aspnetzero:
public async Task<List<DMNCCThueSuatDto>> GetDSThueSuat()
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
var lstthueSuat = await _dmThueSuatRepository.Query(t => t.Where(i =>
i.IsDeleted == false)).OrderBy("thuesuat_ma asc").ToListAsync();
return ObjectMapper.Map<List<DMNCCThueSuatDto>>(lstthueSuat);
}
}
I expected a list of DMNCCThueSuatDto is returned but the error
Cannot create a DbSet for 'DM_NCC_ThueSuat' because this type is not
included in the model for the context.
is always displayed.
Also, i had myown a declaration
public virtual DbSet DS_ThueSuat { get; set; }
in my DBContext.
In my mariadb database, i had a table called "vs_dm_ncc_thuesuat"
and i have already declare a class for mapping to the table above
namespace VS.vHoaDon.Domains.DanhMuc.DMNhaCungCap
{
[Table("vs_dm_ncc_thuesuat")]
[MultiTenancySide(MultiTenancySides.Host)]
public class DM_NCC_ThueSuat : FullAuditedEntity
{
public int ThueSuat_Ma { get; set; }
public string ThueSuat_Ten { get; set; }
public int ThueSuat_GiaTri { get; set; }
public bool ThueSuat_HieuLuc { get; set; }
public DateTime? ThueSuat_BatDau { get; set; }
public DateTime? ThueSuat_KetThuc { get; set; }
}
}
I don't know why?
Any helps is appreciated.
Thank you so much.

ASP.NET MVC 4 - Create a ViewModel from a base class (Model)

There is a class (Model) User.cs:
namespace BookStore
{
using System;
using System.Collections.Generic;
public class User
{
public int user_id { get; set; }
public string user_login_name { get; set; }
public string user_first_name { get; set; }
public string user_last_name { get; set; }
}
}
I want to create a ViewModel to then use it in Views. How should I do it? I create ViewModels folder in the project, create a class UserViewModel.cs in it, then what? I just copy and paste the original User.cs content and put limitations? Like this:
namespace BookStore.Models
{
public class UserViewModel
{
[Editable(false)]
public int user_id { get; private set; }
public string user_login_name { get; set; }
public string user_first_name { get; set; }
public string user_last_name { get; set; }
}
}
I did so and now my UserController says it can't implicitly convert type BookStore.User to BookStore.UserViewModel:
public class UserController : Controller
{
private DBEntities db = new DBEntities();
public ActionResult UserDetails()
{
UserViewModel user = db.Users.FirstOrDefault(u => u.user_login_name==User.Identity.Name);
if (user == null)
return RedirectToAction("Create");
else
return View(user);
}
I know it is important in MVC to separate concerns, domain models and view models should be used for different purposes, but why is there no any detailed info on how to create ViewModels correctly?

DropdownList selected value not saved in database

I need big help from here i am new to Asp.net MVC 4 Application development , actually i faced a problem when i save my dropdownlist selected value in a database ,after i click my submit button.
I use Debug pointer to check values in a HTTP post object but it doesn't contain dropdownlist select value it always display null value in a division raw I need some expert advice to solve that problem i go through the several examples and try several times but still i haven't proper solution for that.
Model class:
public partial class tblEmployee
{
public int EmployeeId { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public Nullable<System.DateTime> DateOfJoin { get; set; }
public string Position { get; set; }
public string Office { get; set; }
public string Division { get; set; }
public Nullable<decimal> Salary { get; set; }
public virtual tblDivision Divisions { get; set; }
}
public partial class tblDivision
{
public int value { get; set; }
public string Division { get; set; }
public Nullable<int> SelectId { get; set; }
}
Controller class:
namespace EmpiteHrSystem.Controllers
{
public class EmployeeController : Controller
{
private EmpiteContext db = new EmpiteContext();
public ActionResult Create()
{
ViewBag.DivisionOptions = new SelectList(db.tblDivisions, "value","Division");
return View();
}
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(tblEmployee tblemployee)
{
if (ModelState.IsValid)
{
try
{
db.Entry(tblemployee).State = EntityState.Added;
db.tblEmployees.Add(tblemployee);
db.SaveChanges();
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
}
}
}
View:
#model EmpiteHrSystem.Models.tblEmployee
#{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml";}
#Html.EditorFor(model => model.EmployeeId)
#Html.ValidationMessageFor(model => model.EmployeeId)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#*#Html.EditorFor(model => model.Office)*#
#Html.DropDownList("DivisionOptions")
#Html.ValidationMessageFor(model => model.Division)
#Html.ActionLink("Back to List", "Index")
Your DivisionOptions drop down list is not being bound back to the model properly because it is the wrong name. Your model is looking for a property with the name Division while your drop down list is being bound to DivisionOptions. You have a few options.
Use a strongly typed helper
#Html.DropDownListFor(x=>x.Division, (SelectList)ViewBag.DivisionOptions)
Rename your currrent code and pass in the SelectList
#Html.DropDownList("Division", (SelectList)ViewBag.DivisionOptions)

Using ComplexType with ToList causes InvalidOperationException

I have this model
namespace ProjectTimer.Models
{
public class TimerContext : DbContext
{
public TimerContext()
: base("DefaultConnection")
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<ProjectTimeSpan> TimeSpans { get; set; }
}
public class DomainBase
{
[Key]
public int Id { get; set; }
}
public class Project : DomainBase
{
public UserProfile User { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IList<ProjectTimeSpan> TimeSpans { get; set; }
}
[ComplexType]
public class ProjectTimeSpan
{
public DateTime TimeStart { get; set; }
public DateTime TimeEnd { get; set; }
public bool Active { get; set; }
}
}
When I try to use this action I get the exception The type 'ProjectTimer.Models.ProjectTimeSpan' has already been configured as an entity type. It cannot be reconfigured as a complex type.
public ActionResult Index()
{
using (var db = new TimerContext())
{
return View(db.Projects.ToList);
}
}
The view is using the model #model IList<ProjectTimer.Models.Project>
Can any one shine some light as to why this would be happening?
Your IList<ProjectTimeSpan> property is not supported by EF. A complex type must always be part of another entity type, you cannot use a complex type by itself. If you absolutely need to have ProjectTimeSpan as a complex type, you will need to create a dummy entity type that only contains a key and a ProjectTimeSpan, and change the type of Project.TimeSpans to a list of that new type.

Entering data from asp.net mvc

I would like to automatically insert username, userid, date such thing from (server side) model in asp.net mvc how do i insert in such model ?
public class Enquiry
{
public int ID { get; set; }
public DateTime Date { get; set; }
[Required]
public string Name { get; set; }
public string Contactno { get; set; }
public string Remarks { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string Editdate { get; set; }
public string status { get; set; }
}
public class EnquiryDBContext : DbContext
{
public DbSet<Enquiry> Enquiries { get; set; }
}
How do i insert date from controller or model without having it to be inserted from view ?
my controller is like this
[HttpPost]
public ActionResult Create(Enquiry enquiry)
{
if (ModelState.IsValid)
{
db.Enquiries.Add(enquiry);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(enquiry);
}
ktm,
just populate the date in the HttpGet action and then pass that to the view. here's a snippet:
Controller:
[HttpGet]
public ActionResult Create()
{
Enquiry enquiry = new Enquiry();
enquiry.Date = DateTime.UtcNow;
// set any other required properties
return View(enquiry);
}
in your create view:
// ref to base model
#model yournamespace.Models.Enquiry
// add the date from the controller as a hidden field
#Html.HiddenFor(m => m.Date)
<!-- other properties -->
then, just use your HttpPost actionmethod as before -voila!

Resources