I don't know how to pass DateTime value to my model from Html.BeginForm.
I don't want to use calender.
Can I use hidden field to pass it to model?
public partial class gpAdmin
{
public long Id { get; set; }
public string name { get; set; }
public System.DateTime registerDate { get; set; }
}
and view
#using (Html.BeginForm())
{
<div>
<div class="editor-label">
#Html.Label("Name")
#Html.TextBoxFor(a => a.name)
#Html.ValidationMessageFor(m => m.name)
</div>
......
}
and register controller
[HttpPost]
public ActionResult Index(gpAdmin admin)
{
if (ModelState.IsValid)
{
ds.gpAdmin.Add(admin);
ds.SaveChanges();
}
return view();
}
What should I do for the registerDate field, which is a DateTime type?
You may use #Html.EditorFor(a=>a.registerDate).
You may also consider adding attributes to the field
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public System.DateTime registerDate { get; set; }
If you want that to be hidden use #Html.HiddenFor(a=>a.registerDate)
But if you have to use #Html.HiddenFor I recommend not using it at all and initializing default date in the model constructor itself.. use the following code
public partial class gpAdmin
{
public gpAdmin()
{
registerDate = DateTime.Now;
}
public long Id { get; set; }
public string name { get; set; }
public System.DateTime registerDate { get; set; }
}
Related
I am working on a CRUD ASP.NET Core MVC application. I have two entities Product and Categrory, i want to populate a DropDownlist from model "Category" in the "Product" View. Here is my code:
public class Product
{
[Key]
public int ProductId { get; set; }
public string ProductName { get; set; }
public string Description { get; set; }
[ForeignKey("CategoryId")]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
[Key]
public int CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
ProductController.cs:
[HttpGet]
public IActionResult Create()
{
List<Category> categories = _dbcontext.Category.ToList();
ViewBag.bpCategories = new SelectList(categories, "CategoryId", "Category");
Product product = new Product();
return View(product);
}
and in Create.cshtml i used this code to display the Dropdownlist:
<div class="form-group">
<label asp-for="CategoryId" class="control-label"></label>
<select asp-for="CategoryId" class="form-control" asp-items="ViewBag.bpCategories"></select>
</div>
But this code throws Nullreference exception. Any suggestions??
Maybe an error comes from SelectList constructor. Try this:
ViewBag.bpCategories = new SelectList(categories, "CategoryId", "CategoryName");
Use "CategoryName" as text value instead of "Category".There is no Category property in your Category class.
The third parameter is the data text field. Check here:
https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#system-web-mvc-selectlist-ctor(system-collections-ienumerable-system-string-system-string)
I'm new to MVC and are having a hard time figuring some "basic" things out.
I have a ViewModel shaped as follows:
public class ProjectViewModel
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
[Required]
[Display(Name = "Final due date")]
public DateTime FinalDueDate { get; set; }
[Required]
[Display(Name = "Attached equipment")]
public Equipment AttachedEquipment { get; set; }
}
In my Create view I would like to be able to select the value for AttachedEquipment from a dropdownlist. I have a table in my database with all the available Equipments.
I know there is an #Html helper #Html.DropDownListFor which serves this very purpose. However I fail to see how I get the values from the database and spit them out into my view.
My ProjectController looks like this:
private AdventureWorks db = new AdventureWorks();
// GET: Project
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Create()
{
// I'm guessing this is where I need to do some magic
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProjectViewModel model)
{
if (ModelState.IsValid)
{
var project = new Project
{
Title = model.Title,
Description = model.Description,
CreatedDate = DateTime.Now,
FinalDueDate = model.FinalDueDate,
Equipment = model.Equipment
};
db.Projects.Add(project);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
How do I load the Equipment values from my DB into a dropdownlist in my Create view?
Since you cant bind a dropdownlist to the complex object AttachedEquipment, I would change the view model to include properties for the selected equipment and a SelectList for the options
public class ProjectViewModel
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
[Required]
[Display(Name = "Final due date")]
public DateTime FinalDueDate { get; set; }
[Required(ErrorMessage="Please select equipment)]
public int? SelectedEquipment { get; set; }
public SelectList EquipmentList { get; set; }
}
Controller
public ActionResult Create()
{
ProjectViewModel model = new ProjectViewModel();
// Assumes your Equipments class has properties ID and Name
model.EquipmentList = new SelectList(db.Equipments, "ID", "Name");
return View(model);
}
View
#model ProjectViewModel
#using(Html.BeginForm())
{
....
#Html.DropDownListFor(m => m.SelectedEquipment, Model.EquipmentList, "--Please select--")
....
}
Alternatively you can bind to m => m.AttachedEquipment.ID (assuming Equipment contains property ID)
I have a asp mvc 5 project using entity framework code-first. I created the controllers and views with scaffolding. Although i have not specified in the model that the Due date be [Required] and the item in the table has a value of NOT NULL.
Yet I am still getting this message on the POST
The DueDate field is required.
The model is really basic
public class Project
{
public int ProjectId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime DueDate { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
}
}
This is a Datetime2 datatype using EditorFor
<div class="input-group">
#Html.EditorFor(model => model.DueDate, new { #class = "form-control datepicker" })
<div class="input-group-addon">
<i class="entypo-calendar"></i>
</div>
</div>
It is also using jquery bootstrap datepicker, Although i doubt these has any effect on this functionality. Really confused how this field is a required field yet it has not been set as such in any area of the solution or database.
That's normal. DateTime is a value type meaning that it will always require a value. The model metadeata provider in ASP.NET MVC automatically adds the required attribute to non-nullable data types. You could use a nullable DateTime:
public class Project
{
public int ProjectId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime? DueDate { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
}
I have a ViewModel as below:
public class CheckoutViewModel
{
public string ProductNumber { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public Input UserInput;
public class Input
{
public string Email { get; set; }
public string Phone { get; set; }
}
}
And an action like this:
[HttpPost]
public ActionResult Index(CheckoutViewModel model)
{
// ...
return View();
}
And my model has bound as below:
#model GameUp.WebUI.ViewModels.CheckoutViewModel
#using (Html.BeginForm("Index", "Checkout", FormMethod.Post))
{
#Html.AntiForgeryToken()
<!-- some HTML -->
#Html.LabelFor(m => m.UserInput.Email)
#Html.TextBoxFor(m => m.UserInput.Email)
#Html.LabelFor(model => model.UserInput.Phone)
#Html.TextBoxFor(model => model.UserInput.Phone)
<button>Submit</button>
}
When I submit the form, the UserInput is null. I know ASP.NET MVC is able to bind nested types but in this code is not. Also I can get the Email and Phone values by:
var email = Request.Form["UserInput.Email"];
var phone = Request.Form["UserInput.Phone"];
Maybe I do something wrong! It's a simple model binding you can find everywhere in the web.
You forgot to put a setter in your UserInput, I don't think the setter is automatic. Anyway you can make it work by just putting a getter/setter in your UserInput and no need to do extra in your controller method:
public Input UserInput { get; set; }
Your complete model:
public class CheckoutViewModel
{
public string ProductNumber { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public Input UserInput { get; set; }
public class Input
{
public string Email { get; set; }
public string Phone { get; set; }
}
}
here is my model
namespace chPayroll.Models.CustInformations
{
public class CustContact
{
public int cId { get; set; }
public int cNoType { get; set; }
public string cNo1 { get; set; }
public string cNo2 { get; set; }
public string cNo3 { get; set; }
public List<CustContact> contact { get; set; }
}
}
here is my editorTemplates
#model chPayroll.Models.CustInformations.CustContact
#Html.TextBoxFor(model => model.cNo1)
#Html.TextBoxFor(model => model.cNo2)
#Html.TextBoxFor(model => model.cNo3)
I need to show three textbox for taking email,three text box for taking telephone no. in view. how can I add the items to the list contact defined in the model so that it shows like this
email:--textbox1----textbox2----textbox3--
telephone:--textbox1----textbox2----textbox3--
and sends value to the controller
actually I am trying to send my data in list named contact here ie inside list at
index 0-email1-email2-email3
index 1-tel1-tel2-tel3
#Sanjay: you have a strange construct in your view model:
public class CustContact
{
public List<CustContact> contact;
}
Even if it compiles and machine understands it, I wouldn't use it as it is - you trying to lift yourself from the ground by pulling your hair up :)
It should be defined something along these lines (following your naming conventions & logic):
public class CustContact // single
{
public int cId { get; set; }
public int cNoType { get; set; }
public string cNo1 { get; set; } // those are actual phones, emails etc data
public string cNo2 { get; set; }
public string cNo3 { get; set; }
}
public class CustContacts // plural
{
public List<CustContact> Contacts;
}
View:
#model CustContacts
#EditorFor(m => Model)
Editor template:
#model CustContact
#Html.EditorFor(m => m.cNo1)
#Html.EditorFor(m => m.cNo2)
#Html.EditorFor(m => m.cNo3)
For brevity, we don't deal here with annotations, decorations, error handling etc.
Hope this helps.
Based on the comment on the question, I would build the models as below
public class CustContact
{
public int cId { get; set; }
public int cNoType { get; set; }
public string cNo1 { get; set; }
public string cNo2 { get; set; }
public string cNo3 { get; set; }
}
public class Customer
{
public CustContact Email {get; set;}
public CustContact Telephone {get; set;}
}
then create an editor template for Customer and in that editor template have following logic
#Html.EditorFor(model => model.Email)
#Html.EditorFor(model => model.Telephone)
Hope this helps