weixin_33699914 2016-02-17 20:54 采纳率: 0%
浏览 59

将DateTime传递给控制器

I want to pass DateTime that was selected in datetimepicker in controller.

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />

<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('#datetimepicker1').datetimepicker();
        });
    </script>
</div>
</div>

Controller:

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetData(DateTime dateTime)
    {
        return View();
    }
}

What is the best way to do this? Use Ajax? How to do it correct?

 $.ajax({
    url: "/Home/GetData",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(????),
    contentType: "application/json; charset=utf-8",
    success: function (result) { }, 
    failure: function (r, e, s) { alert(e); } 
 });
  • 写回答

3条回答 默认 最新

  • weixin_33694620 2016-02-17 21:58
    关注

    You can basically listen for the change event on the input field and send the value of that. You don't really need to stringify it as it is simple value you are sending.

    $(function(){
    
      $("#datetimepicker1").change(function(){
         var v = $(this).val();
         if(v.length>0)
         {
              var url = "@Url.Action("GetData","Home")" +"? dateTime="+v;
              $.get(url, function(re) {
                  //do something with the re
                  console.log(re);
              });
         }
    
      });
    
    
    });
    

    I used the Url.Action method to generate the correct relative url to the action method. This code will work if your js code is inside a razor view. If your code is inside an external js file, Use the method explained in this post.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘