将值从 MVC 控制器传递给 javascript 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10691079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass values from MVC controller to javascript code
提问by ZVenue
I need to pass list/json/array of dates information to a Jquery UI Datepicker dynamically through a jsonresult in a MVC controller.
我需要通过 MVC 控制器中的 jsonresult 将日期信息列表/json/array 动态传递给 Jquery UI Datepicker。
Following the link below, I am able to highlight selected dates in the datepicker control. http://jquerybyexample.blogspot.com/2012/05/highlight-specific-dates-in-jquery-ui.html
按照下面的链接,我可以突出显示日期选择器控件中的选定日期。 http://jquerybyexample.blogspot.com/2012/05/highlight-specific-dates-in-jquery-ui.html
< script type ="text/javascript">
$(document).ready( function () {
var SelectedDates = {};
SelectedDates[ new Date('05/28/2012' )] = new Date( '05/28/2012' );
SelectedDates[ new Date('05/29/2012' )] = new Date( '05/29/2012' );
SelectedDates[ new Date('05/30/2012' )] = new Date( '05/30/2012' );
//want to replace the above three lines with code to get dates dynamically
//from controller
$( '#releasedate' ).datepicker({
dateFormat: "mm/dd/yy" ,
numberOfMonths: 3,
duration: "fast" ,
minDate: new Date(),
maxDate: "+90" ,
beforeShowDay: function (date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true , "Highlighted", Highlight];
}
else {
return [true , '', '' ];
}
}
});
The above code will highlight those specific three dates on the calendar control(UIDatepicker).Instead of hard coding dates like above... My challenge is to get these dates dynamically from a controller and pass it on to the var SelectedDates in javascript above.
上面的代码将突出显示日历控件(UIDatepicker)上的那些特定三个日期。而不是像上面那样硬编码日期......我的挑战是从控制器动态获取这些日期并将其传递给上面javascript中的var SelectedDates。
Controller jsonresult code:
控制器jsonresult代码:
public JsonResult GetReleasedDates(string Genre)
{
var relDates = service.GetDates(Genre)//code to get the dates here
return Json(relDates, JsonRequestBehavior .AllowGet);
//relDates will have the dates needed to pass to the datepicker control.
}
Thanks for the help.
谢谢您的帮助。
回答by Darin Dimitrov
The first possibility is to use a model that will be directly serialized into JSON:
第一种可能性是使用将直接序列化为 JSON 的模型:
public ActionResult Index()
{
// TODO: obviously those will come from your service layer
var selectedDates = new Dictionary<string, DateTime>
{
{ new DateTime(2012, 5, 28).ToString("yyyy-M-dd"), new DateTime(2012, 5, 28) },
{ new DateTime(2012, 5, 29).ToString("yyyy-M-dd"), new DateTime(2012, 5, 29) },
{ new DateTime(2012, 5, 30).ToString("yyyy-M-dd"), new DateTime(2012, 5, 30) },
};
return View(selectedDates);
}
and in the view:
并在视图中:
@model IDictionary<string, DateTime>
<script type ="text/javascript">
$(document).ready(function () {
var selectedDates = @Html.Raw(Json.Encode(Model));
$('#releasedate').datepicker({
dateFormat: "mm/dd/yy",
numberOfMonths: 3,
duration: "fast",
minDate: new Date(),
maxDate: "+90",
beforeShowDay: function (date) {
var key = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
var highlight = selectedDates[key];
if (highlight) {
return [true, "Highlighted", highlight];
}
else {
return [true, '', ''];
}
}
});
});
</script>
The other possibility is to use AJAX to retrieve the selectedDates
later:
另一种可能性是使用 AJAX 来检索selectedDates
后者:
public ActionResult Index()
{
return View();
}
public ActionResult GetSelectedDates()
{
// TODO: obviously those will come from your service layer
var selectedDates = new Dictionary<string, DateTime>
{
{ new DateTime(2012, 5, 28).ToString("yyyy-M-dd"), new DateTime(2012, 5, 28) },
{ new DateTime(2012, 5, 29).ToString("yyyy-M-dd"), new DateTime(2012, 5, 29) },
{ new DateTime(2012, 5, 30).ToString("yyyy-M-dd"), new DateTime(2012, 5, 30) },
};
return Json(selectedDates, JsonRequestBehavior.AllowGet);
}
and then:
进而:
<script type ="text/javascript">
$(document).ready(function () {
$.getJSON('@Url.Action("GetSelectedDates")', function(selectedDates) {
// Only inside the success callback of the AJAX request you have
// the selected dates returned by the server, so it is only here
// that you could wire up your date picker:
$('#releasedate').datepicker({
dateFormat: "mm/dd/yy",
numberOfMonths: 3,
duration: "fast",
minDate: new Date(),
maxDate: "+90",
beforeShowDay: function (date) {
var key = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
var highlight = selectedDates[key];
if (highlight) {
return [true, "Highlighted", highlight];
}
else {
return [true, '', ''];
}
}
});
});
});
</script>
回答by acuntex
There is a library to exchange data from controller to javascript without the need of a further ajax call or inline javascript. If you need the data on every page, you could use it in a filter.
有一个库可以将数据从控制器交换到 javascript,而无需进一步的 ajax 调用或内联 javascript。如果您需要每个页面上的数据,您可以在过滤器中使用它。
With the library you could just write the following code in your MVC Controller Action:
使用该库,您可以在 MVC 控制器操作中编写以下代码:
// Add the dates as objects to javascript - The object should only contain data
// which should be exposed to the public.
this.AddJavaScriptVariable("DatePickerController.Dates", service.GetDates(Genre));
// Execute the initialization function when the DOM has been loaded
// The function can be in a javascript file
this.AddJavaScriptFunction("DatePickerController.Ready");
Your javascript file could look like this:
您的 javascript 文件可能如下所示:
var DatePickerController = {
Dates: null,
Ready: function() {
$("#releasedate").datepicker({
dateFormat: "mm/dd/yy" ,
numberOfMonths: 3,
duration: "fast" ,
minDate: new Date(),
maxDate: "+90" ,
beforeShowDay: function (date) {
var Highlight = DatePickerController.Dates[date];
if (Highlight) {
return [true , "Highlighted", Highlight];
}
else {
return [true , '', '' ];
}
}
});
}
};
Note: You maybe have to create a special model for the dates you pass with this.AddJavaScriptVariable which is compatible to the datepicker.
注意:您可能需要为使用 this.AddJavaScriptVariable 传递的日期创建一个特殊模型,该模型与日期选择器兼容。
回答by Vismari
Make an ajax call:
进行ajax调用:
<script type ="text/javascript">
$(document).ready( function () {
var SelectedDates = {};
//SelectedDates[ new Date('05/28/2012' )] = new Date( '05/28/2012' );
//SelectedDates[ new Date('05/29/2012' )] = new Date( '05/29/2012' );
//SelectedDates[ new Date('05/30/2012' )] = new Date( '05/30/2012' );
$.ajax({
url:'url'
,data:{}
,type:'get'
,success:function(data) {
for(var i = 0, i < data.length; i++) {
SelectedDates.push(new Date(data[i]));
}
$( '#releasedate' ).datepicker({
dateFormat: "mm/dd/yy" ,
numberOfMonths: 3,
duration: "fast" ,
minDate: new Date(),
maxDate: "+90" ,
beforeShowDay: function (date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true , "Highlighted", Highlight];
}
else {
return [true , '', '' ];
}
}
});
});
});
</script>
回答by Jason Meckley
make an ajax call to get the dates. upon success of the ajax request, configure the datapickers with the results.
进行 ajax 调用以获取日期。在 ajax 请求成功后,使用结果配置数据选择器。
var configureDatePickers = function(dates){
//setup datepicker in here...
};
$.get('url to get dates', {Genre: smoething}).success(configureDatePickers);
One other recomendation. the default json serializer doesn't play well with the datetime object. therefore I would suggest returning the dates as strings before serializing. example:
另一项推荐。默认的 json 序列化器不能很好地与 datetime 对象配合使用。因此我建议在序列化之前将日期作为字符串返回。例子:
var dates = Data.GetDates(genre).Select(x=>x.ToString("MM-dd-yyyy")).ToArray();
return Json(dates);