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.

    评论

报告相同问题?