How can I access ViewData in a PartialView from jQuery in MVC? - asp.net

I have a View loading a PartialView via jQuery. The PartialView has ViewData that the jQuery needs to access, but I can't seem to get to it from the jQuery. The code below uses the HighChart jQuery plugin (and it is just test code taken from the HighChart example page):
<script type="text/javascript">
var chart1; // globally available
$(document).ready(function () {
$('#reportButton').click(function (event) {
var actionUrl = '<%= Url.Action("UserReport") %>';
var customerId = $('#customersId').val();
var month = $('#monthsId').val();
var employees = '<%= ViewData["Employees"] %>'
alert(employees);
$.get(actionUrl, { customerId: customerId, month: month }, function (data) {
$('#result').html(data);
getHighChart();
});
});
});
function getHighChart() {
var employees = '<%= ViewData["Employees"] %>'
alert(employees);
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-1',
defaultSeriesType: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: [employees]
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
}
</script>
This jQuery is in the main view, because I don't know how I could put it in the PartialView with the document ready function. But by putting the call to the HighChart function in the callback of the get() function it works in the partial view. But accessing the ViewData doesn't...
How can I achieve this? I need to get the data from the PartialView action method in order to populate the HighChart data...

The problem is the way ASP.NET traverses the HTML document when rendering.
Even though you have this code executing after the $.get call has finished:
var employees = '<%= ViewData["Employees"] %>'
The ViewData property will get evaluated render-time (e.g before this code is executed).
What i recommend:
Declare a hidden field in your partial view, and place the ViewData in there:
<input type="hidden" id ="Employees_ViewData" value="<%: ViewData["Employees"] %>" />
That will get evaluated when the partial view is rendered.
Then you can access it via jQuery:
var employees = $('#Employees_ViewData').val();

Related

Kendo AutoComplete Empty Filter in Querystring - serverfiltering

I'm trying to use serverfiltering for autocomplete in Kendo UI (ASP.NET 5, MVC6)
Due to fact that Autocomplete isn't available in MVC Wrapper, i had to use the code below:
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
serverOperation: true,
type: "aspnetmvc-ajax",
transport: {
read: {
url: "#Url.Content("~/api/Get")",
type: "GET"
}
},
schema: {
data: "Data",
total: "Total"
}
})
$("##Model.Name").kendoAutoComplete({
placeholder: "#Model.Watermark",
minLength: 3,
filter: "contains",
dataSource: dataSource
});
</script>
The problem is that querystring send to controller looks like this :
?sort=&group=&filter=
So it doesn't include any filter information
On serverside im trying to map it to DataSourceRequest
Right now im using following workaround to pass additional parameter to do serversidefiltering but still i'd like to use kendo native filtering for this:
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
serverOperation: true,
type: "aspnetmvc-ajax",
transport: {
read: {
url: "#Url.Content("~/api/Get")",
type: "GET",
data: onAdditionalData
}
},
schema: {
data: "Data",
total: "Total"
}
})
$("##Model.Name").kendoAutoComplete({
placeholder: "#Model.Watermark",
minLength: 3,
filter: "contains",
dataSource: dataSource
});
function onAdditionalData() {
return {
text: $("##Model.Name").val()
};
}
</script>
Controller code:
[Route("api/Get")]
[HttpGet]
public JsonResult Get([DataSourceRequest] DataSourceRequest request, string text = "")
{
var list = (new List<string>() { "value1", "value2", "value3", "test" } ).AsQueryable();
return Json(list.Where(x => x.Contains(text)).ToDataSourceResult(request));
}

Jquery slider. On Slider Stop raise server side event

i would like to raise a server side event at the mouseup event of the jquery slider.
How can i accomplish this? Can you point me a good place to start?
The server side code i would like to call is
Private Sub LoadBlock(ByVal AA As Integer)
'A lot of stuff here
End Sub
The value gathered from the Jquery slider event should be passed as a parameter in the procedure above
My current JQuery is
<script type="text/javascript">
$(document).ready(function () {
var Country = ['<% =String.Join("', '", arrayString)%>'];
$('#slider-range-max').slider({
max: '<%= arrayLength%>',
min: 0,
value: '<%= iValue%>',
slide: function (event, ui) {
var splitValues = Country[ui.value].split("~");
$('#lblGame').html(splitValues[0]);
$('#hpHome').html(splitValues[1]);
},
stop: function (event, ui) { }
});
});
</script>
Finally this is not a homework!!!
<script type="text/javascript">
$(document).ready(function () {
var Country = ['<% =String.Join("', '", arrayString)%>'];
$('#slider-range-max').slider({
max: '<%= arrayLength%>',
min: 0,
value: '<%= iValue%>',
slide: function (event, ui) {
var splitValues = Country[ui.value].split("~");
$('#lblGame').html(splitValues[0]);
$('#hpHome').html(splitValues[1]);
},
stop: function (event, ui) {
//bof:AJAX hit
var path="YourPageName.aspx/NewMethod";
$.ajax({
url:path,type:"POST",cache:"false",
dataType:"json",contentType:"application/json; charset=utf-8",
data:"{'str1':'Some Temp String'}",
success:function(response){alert("response is "+response.d);
},error:function(){
}
});
//eof:AJAX hit
}
});
});
</script>
and in code behind:
<System.Web.Services.WebMethod> _
Public Shared Function NewMethod(str1 As String) As String
'make same name of variable as in json data
'do your server side stuff
Return "Success"
End Function
I don't have tested this code but certainly this will help you
take one button
<asp:Button ID="img_update" runat="server" Text="Submit" style='display:none' OnClick="img_update_Click" />
your method non-static method
protected void img_update_Click(object sender, EventArgs e)
{
//your code -behind
}
Now your jquery will looks like
<script type="text/javascript">
$(document).ready(function () {
var Country = ['<% =String.Join("', '", arrayString)%>'];
$('#slider-range-max').slider({
max: '<%= arrayLength%>',
min: 0,
value: '<%= iValue%>',
slide: function (event, ui) {
var splitValues = Country[ui.value].split("~");
$('#lblGame').html(splitValues[0]);
$('#hpHome').html(splitValues[1]);
},
stop: function (event, ui) {
document.getElementById('client id of button').click();
}
});
});
</script>
I hope this will give you better idea how to implement non-static method regards.....:)

Bind Kendo UI treeview to Json data returned by ASP.Net .ashx handler

I want to create a simply treeview with the Kendo UI treeview widjet.
I read the documentation, but I can't go further the first step: Bind a simple, simple non-nested json value:
In my head section i put:
<script>
$(document).ready(function () {
var homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "kendoTWData.ashx",
dataType: "json"
}
},
schema: {
model: {
id: "EmployeeId",
FullName: "FullName"
}
}
});
$("#treeview").kendoTreeView({
dataSource: homogeneous,
dataTextField: "FullName",
dataValueField: "id"
});
});
</script>
The handler "kendoTWData.ashx" correctly return: {"EmployeeId":1,"FullName":"AName"}
But nothing appears.
Thanks in advance.
It should return an array and not an object. It should be:
[{"EmployeeId":1,"FullName":"AName"}]
This is because the tree might have multiple nodes at root level.

Dynamic resize iframe in FullCalendar

I have Fullcalendar opening in iframe. I have a script from dyn-web.com on parent page that resizes Iframe and this works fine most of the time:
function setIframeHeight(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px";
ifrm.style.height = getDocHeight( doc ) + 5+"px";
ifrm.style.visibility = 'visible';
}
When I open the calendar initially it resizes fine, but when I select another month that has a longer page render, it will not resize.
How can I invoke the resize on the parent window?
This is the start of my calendar but I cannot figure out the syntax to dynamically call resize. I have played with the height parameter, but it needs to be dynamic:
$('#calendar').fullCalendar({
month: <%=monthStart%>,
year: <%=yearStart%>,
eventSources:
[
{ url: <%=esource%>,
type: 'GET',
error: function() {
alert('there was an error while fetching events!');
}
},
You need to do something like this:
$('#calendar').fullCalendar({
month: <%=monthStart%>,
year: <%=yearStart%>,
eventSources:
[
{ url: <%=esource%>,
type: 'GET',
error: function() {
alert('there was an error while fetching events! ');
}
},
viewDisplay: function(view) {
parent.setIframeHeight(iframeId) ;
},
The viewDisplay handler is called every time the month/week/day view is changed. You can also use the windowResize handler to capture an event fired after the resize has actually taken place.

Viewdata not showing in partial view

Hi guys i have controller which returns a partial view, the controller is called by ajax script. The partical view has no problem showing viewdata first time, But when ajax script is invoked second time the partical view does not update it self with new viewdata.
code for controller
[HttpGet]
public ActionResult getPart(int id)
{
ViewData["partical"] = id;
return PartialView("test");
}
code for partial view
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PovertyBayHotel.Models.testmodel>" %>
<p>just a test</p>
<%: ViewData["partical"]%>
and the ajax which call the controller
<script type="text/javascript">
$(document).ready(function () {
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
});
});
</script>
Might be a caching issue. Try HTTP POST instead of GET or set the ifModified and cache options to false as below:
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
ifModified: false,
cache: false,
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
Also, try to debug your code and see really what is going on.
Edit:
The problem has been solved by changing $('#ExtraBox').replaceWith(data); with $('#ExtraBox').html(data);.

Resources