ASP.NET Calendar OnSelectionChanged handler not getting called

﹥>﹥吖頭↗ 提交于 2019-12-06 16:02:02

<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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!