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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料