Can some please tell me why the event handler named "MyCalendar_SelectionChanged" is not getting executed when I click on a day within calendar control? This is the simple aspx code from a sample ASP.NET MVC2 application:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<script runat="server">
private void MyCalendar_SelectionChanged (object sender, System.EventArgs e)
{
//lbl1.Text = Calendar1.SelectedDate.ToString();
Console.WriteLine("test");
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="s开发者_如何学JAVAerver">
<form id="Form1" runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<div>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="MyCalendar_SelectionChanged" />
</div>
</form>
</asp:Content>
<asp:Calendar runat="server" ... />
is a server control that relies on ViewState and PostBack which are notions that no longer exist in ASP.NET MVC so you shouldn't be using any server controls. Because there are no postbacks and view callbacks your function won't be triggered. Also make sure you remove the runat="server"
tag from your form and use HTML helpers to generate forms.
To implement a calendar in ASP.NET MVC you may checkout the jQuery UI datepicker.
So here's how you might proceed:
As always you start with the M(odel) in MVC which will represent the information you are willing to show (in your case a date):
public class MyViewModel
{
public DateTime Date { get; set; }
}
Then you get to the C(ontroller) in MVC:
public class HomeController: Controller
{
// used to render the view
public ActionResult Index()
{
var model = new MyViewModel
{
Date = DateTime.Now
};
return View(model);
}
// will be called when the form is submitted
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
Then the V(iew) in MVC:
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.MyViewModel>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.EditorFor(x => x.Date) %>
<input type="submit" value="OK" />
<% } %>
</asp:Content>
and then you could have a separate javascript file in which you would attach the datepicker after having included jquery and jquery UI scripts to your page:
$(function() {
$('#Date').datepicker();
});
and if you wanted the form to automatically submit when the user picks a value:
$(function() {
$('#Date').datepicker({
onSelect: function(dateText, inst) {
$('form').trigger('submit');
}
});
});
A good place to start with MVC is here: http://asp.net/mvc
精彩评论