Setting current controller name to a knockout observable on page load using asp.net mvc - asp.net-mvc

I have the following view model in a separate .JS file:
var vm = {
ControllerName:ko.observable(),
getData: function () {
$.ajax({
type: 'GET',
url: '/'+this.ControllerName+'/GetData',
contentType: "application/json; charset=utf-8",
dataType: "json",
data:jsonData,
success: function(data){
// code to bind the data
}
});
} }
$(function () {
ko.applyBindings(C1ViewModel);
C1ViewModel.getVisibleAndInvisibleColumns(); });
I have to set the ControllerName observable with the current asp.net mvc controller name and use this observable in the getData function so that the controller name is always dynamic. Since we cannot execute server side razor code in .JS files I would have to pass the current controller name from my markup file where I can get the current controller name by writing server side razor code.
My question is how can I pass a value from my html to my view model, set it in an observable and use it as a global value throughout my view model? Is there any other way to achieve what I am trying to do above?

You can use script tags in your markup to declare a JS variable that sets the controller name. You can then access this is your .JS file:
CSHTML
<script>
var urlForController = "#Url.RouteUrl("DefaultApi",
new { httproute = "",
controller = "ControllerNameHere",
action = "GetData" })";
</script>
You can add additional logic in this code if the controller name varies on some specific criteria.
AJAX Call in JS:
$.ajax({
type: 'GET',
url: urlForController,
contentType: "application/json; charset=utf-8",
dataType: "json",
data:jsonData,
success: function(data){
// code to bind the data
}
});

Related

How to call partial view in script section

I am new in MVC. I have a button when i click it should go to a partial view and return data i need. I do not know how should i achieve that:
Main view:
<script>
if ($("#btnFilter").click(function () {
#{Html.RenderPartial("partialView"); }
}));
</script>
partial view
var dtDrpVals = new selectedDateDrpdnVal();
debugger;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("controller","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": dtDrpVals.drpValue, "dtFrom": dtDrpVals.fromDate, "dtTo": dtDrpVals.toDate }),
success: function (result) {
}
});
In the html define a div where you want the partial to be located in and in the ajax success put the result of the call to the controller into that div, assuming you are returning a partialview:
$("#The id of the div").html(result);
The best way to do it is Make an Action in your ASP.NET controller that returns a Partial View and in your jquery, you should make an AJAX call to that action with required parameters that eventually will return a Partial View to your Jquery, and the data you will receive from your action will be of type 'HTML' and not JSON.
once you receive HTML data in your success function of AJAX call you can replace it with any Div.

Adding Razor content inside Jquery Ajax call

I am trying to add asp.net mvc razor code inside jquery ajax success function. Any idea on tweaking this to work?
$.ajax({
url: controllerUrl,
type: 'POST',
data: { id: 1 },
success: function (response) {
//adding asp.net mvc razor code
#Html.Partial("GetDetails", Model)
}
));
)};

Using PagedList.Mvc for partial page

I have four different tabs in one page and data for each tab is rendered by an ajax call using partial page. Data for tab is loaded by ajax post.
ajax call:
$('#movieDatabase').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '/Admin/GetMovieDatabase',
data: {},
success: function (data) {
$('#view16').html(data);
},
failure: function (response) {
alert('error');
$('#view16').html(response);
}
});
});
This ajax call rendered the partial page. Now I want to do is paging the movie came from database.For this I use PagedList.Mvc. But problem occurred in navigating movie from one page to another. It is done by:
#Html.PagedListPager((IPagedList)Model.MovieInforamtions, page => Url.Action("GetMovieDatabase", new { page }))
But when I click on next page it gives page not found error as I have not written any action in HTTPGet. And If I made above call by HTTPGet, I couldnot render all page but only partial page. My action is..
[HttpPost]
public ActionResult GetMovieDatabase(int? page)
{
var AdminGetMovieDatabaseViewModel = new AdminGetMovieDatabaseViewModel();
var allMovie = _AdminService.getAllMovieInfo();
var pageNumber = page ?? 1;
// if no page was specified in the querystring, default to the first page (1)
var onePageOfMovie = allMovie.ToPagedList(pageNumber, 5);
// will only contain 5 products max because of the pageSize
AdminGetMovieDatabaseViewModel.MovieInforamtions = onePageOfMovie;
return PartialView("MovieDataBasePartialPage", AdminGetMovieDatabaseViewModel);
}
Now How can I render the next page like in ajax call which is done previously?
I put the code in javascript section inside the partial view and works for me.
<script language ="javascript" type="text/javascript">
$('#movieDatabase').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '/Admin/GetMovieDatabase',
data: {},
success: function (data) {
$('#view16').html(data);
},
failure: function (response) {
alert('error');
$('#view16').html(response);
}
});
});
</script>

Anyway to make use of jquery ui tabs spinner with pagemethods?

I am using Jquery ui tabs with asp.net webforms and I'm loading the content with ajax. I actually have two problems
I don't know how to load the content for the first tab load. Right now I use the tabsselect to load content via ajax.
$('#contentHolder').bind( "tabsselect", function(event, ui) {
// run ajax request
});
The build in spinner control only seems to work when I use actual paths for the href. But since I have to use pagemethods I need to use an id instead.
One
Two
Three
// ajax request to pagemethod
$.ajax...
Updated Code
// tab initializaztion
var $tabs = $('#followersTable').tabs({ spinner: 'Loading...' });
$tabs.bind("tabsselect", function(event, ui) {
//LoadTabContent(ui.index);
var request = {
'controlName': 'FollowersTab'
};
$(this).tabs({
ajaxOptions: {
type: "POST",
url: "ajax/Followers.aspx/LoadTabContent",
data: $.toJSON(request),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$(container).html(data.d);
},
error: function () {
}
}
})
});
For your first question:
$("your-tabs-selector-here").tabs( "load" , 0 ); this will force your tab first tab to be loaded via ajax.
If I didn't get it wrong; you could use [WebMethod] for your page methods and you can combine your page methods with UI Tabs ajaxOptions. You can play with ajaxOptions for return type and/or method name ..etc
$( "your-tabs-selector-here" ).tabs({
ajaxOptions: {
type: "POST",
url: "Default.aspx/PageMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}
});

jQuery Mobile: Styling content loaded through AJAX

On a particular jQuery Mobile page I am loading content through an AJAX post. I am then replacing some content in the DOM with the returned HTML.
The returned HTML contains form elements, which I would like jQM to style.
This used to work in beta 1:
$.ajax({
type: 'POST',
url: form.attr("action"),
data: form.serialize(),
success: function (response) {
if (response.worked) {
voucher_area.fadeOut(function () {
$(this).html(response.html).children().page();
$(this).fadeIn();
});
}
else {
Notify.showMessage("Could not update your call with voucher information: " + response.message, "error");
}
},
dataType: "json",
error: function () {
Notify.showMessage("Fatal Error.");
}
});
The call to page on the content would style the content.
However in the latest version this no longer seems to work.
Is there a correct way to style loaded content?
Thanks
You should be able to style content directly using something like: $(this).css({'padding':'5px'}) using the styles of your choice.
Alternatively, you should be able to define the appropriate styles in an external css file as well.

Resources