Adding Razor content inside Jquery Ajax call - asp.net-mvc

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)
}
));
)};

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.

Setting current controller name to a knockout observable on page load using 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
}
});

asp.net mvc4 jquery ui autocomplete not working

I want to use autocomplete widget in asp.net mvc4 app. I was able to call the action to get list of autcompletition values from controller. Unfortunetely I am not able to add it to list of suggestions. I think that .map(data, function(item) in success part of autocomplete ajax call is not working. But I really do not know why. I am sure that all the scripts and css are load corectly. I am stating controller action returining suggestions list, also script in view and response from firebug. I was also trying the demo example from jqueryui page and it was working, but somehow it does not work over my returned data. Can someone help me and tell me why? Thank you in advance.
Action in Controller:
public ActionResult GetCities(int RegionId, string Name)
{
var ret = db.Cities.Where(c => c.RegionId == RegionId &&
c.Name.Contains(Name)).Select(a => new{ CityId = a.CityId, Name = a.Name});
return Json(ret);
}
Script in view:
<script type="text/javascript">
$(function() {
$("#City").autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("GetCities")",
dataType: "json",
contentType: "application/json; charset=utf-8",
method: "POST",
data: "{'RegionId': " + $("#Region").val() + ", 'Name': '" + request.term + "'}",
success: function (data) {
response( $.map( data, function( item ) {
return {
label: item.Name,
value: item.Name
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
Response (from firebug)
[{"CityId":16,"Name":"Kordíky"},{"CityId":94,"Name":"Korytárky"}]
So I find out it was working, the only problem was, that I had breakpoint in visual studio and this breakpoint was supressing autocomplete suggestion list.
for Mvc Artitecture you must delete already imbended #Scripts.Render("~/bundles/Jquery") and #Scripts.Render("~/bundles/Jqueryval")
on all .cshtml files at the end and for also views/Shared/_layout.cshtml at the
end and put our jaquery suitable files on his suitables .cshtmls files in head...and lets enjoy.

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>

JQUERY GET operation not working

I'm having trouble with the following JQuery script
$('#extra_data').append('<div id="tabs-' + (tab_length + 1) + '"></div>');
$.get(url, function(data) {
$('#tabs-' + (tab_length + 1)).html(data);
});
My trouble is that the $.get(..) operation doesn't return any results - although when using firebug it shows the ajax call as expected.
Any clues?
Thanks.
Controller
<HttpPost()> _
Function GetPartialView() As ActionResult
If (Request.IsAjaxRequest()) Then
Return View("PVTest")
Else
Return View()
End If
End Function
I've filtered the request if it is Ajax. You can even pass an object to your partial view.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'Home/GetPartialView',
data: {},
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
$('#extra_data').append(XMLHttpRequest.responseText);
}
});
});
</script>
Partial View (PVTest.ascx)
<%# Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl" %>
<div id="01">
Hello World
</div>
Try load method:
$('#extra_data').append('');
$('#tabs-' + (tab_length + 1)).load(url)
I think you need to use Post and [HttpPost] in ASP.NET MVC, I think there is a security
issue related to GET.
I only seem to use Post operations and remember seeing something about security.
Will see if I can verify that...
ADDED:
see: ASP.NET MVC 2.0 JsonRequestBehavior Global Setting
I would use a POST, as Mark suggested:
$.ajax({
type: 'POST',
url: url,
data: { },
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
var Response = $.parseJSON(XMLHttpRequest.responseText);
}
});
the Response should contain the JSON stream. You can append it to your element.
The controller should do something like this:
<HttpPost()> _
Function DoSomething() As ActionResult
Return (Json(myObject, JsonRequestBehavior.DenyGet))
End Function

Resources