Reputation: 8515
I have to build up a DateTime object from three dropdowns in my view. Building a model binding is a bit too complex for my level of knowledge of MVC now(I read through a few articles). As well I don't have to bind to DateTime property but can rather build my object up from ViewModel properties:
public IEnumerable<SelectListItem> Months
public IEnumerable<SelectListItem> Days
public IEnumerable<SelectListItem> Years
Is it possible to do so ? As well can I perhaps with Ajax set the right amount of days depending on the month and year (taking care of leap years). Any sample codes or articles to refer to are appreciated as I'm still junior at this stuff. Thank you.
Upvotes: 1
Views: 1505
Reputation: 218782
Model Binding is easy. don't be scared about that. Strongly typed views keep your code clean for future readability and maintainability. Microsoft release these new new features for people like us to use. We should not be scared of those !
Why not have a Property to hold the DateTime value and use some other libraries to provide a nice date selection experience to the end user ? jQuery UI calendar is one option you can think of.
http://jqueryui.com/demos/datepicker/
Add the DateTime type property to your ViewModel
public class AlbumViewModel
{
public int ID { set;get;}
public DateTime CreatedDate { set;get;}
}
and in your get action method, you can return an object of this viewmodel to the View.
public ActionResult AddAlbum()
{
AlbumViewModel objItem=new AlbumViewModel();
return View(objItem);
}
Use a strongly typed view with this viewmodel and use jQuery UI calandar to get the calendar.
@model AlbumViewModel
//include jQuery and jQuery UI
@using (Html.BeginForm())
{
<p>Select Date
@Html.TextBoxFor(m=>m.CreatedDate)
<input type="submit" value="Save" />
</p>
}
<script type="text/javascript">
$(function() {
$( "#CreatedDate").datepicker();
});
</script>
and in your post Action
[HttpPost]
public ActionResult AddAlbum(AlbumViewModel objItem)
{
//Check the objItem.CreatedDate here. Save it or do whatever you want
return View(objItem);
}
Upvotes: 1