How to call partial view in script section - asp.net-mvc

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.

Related

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

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>

My asp.net MVC partial view is unresponsive after initial ajax call?

I am working on an asp.net mvc 4 application and I am using a PartialView for a table in the Index view. After I make the initial ajax call the request is successful and the UI is updated accordingly. But when I try to update again, the JavaScript is unresponsive for the click event.
Is this typical?
AJAX call:
$("#button").click(function(){
$.ajax({
url: 'url',
type: "POST",
data: $("#form0").serialize()
}).done(function (allData) {
$("#mypartialId").html(allData);
ResizeContent();
}).fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Something like this is in my controller Index action:
if(Request.IsAjaxRequest())
{
return PartialView("_PartialView", model);
}
return View(model);
Razor Ajax.BeginForm, has id of form0 by default:
#using (Ajax.BeginForm("Index", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "mypartialId"
}))
My partial rendering in Index:
<div id="mypartialId">
#{Html.RenderPartial("_PartialView", Model);}
</div>
This works once but when I click the button switch is in the partialView the JavaScript becomes unresponsive. I am guess its something with the Index view not reloading with the partialView...would there be any way around that?
I used .on() function instead of just the .click() as #Sergey Akopov suggested. After that I had another problem after that because the data coming back was a table, so IE9 was giving me UI problems.
The fix was to remove the white space from the table tags like so, before injecting it into the DOM
var expr = new RegExp('>[ \t\r\n\v\f]*<', 'g');
table = table.replace(expr, '><');
$("#mypartialId").html(table);
Here is a link to the 'td' issue displaying weird in IE9.

Previous ajax request changes the post URL for next form submit

I am making a jQuery ajax request in a asp.net mvc page:
$.ajax({
type: "POST",
url: "/Home/Go",
data: dataObj,
success: function (data) {
// update html here
}
}
});
This call is within a page, which has a form and other elements which submit to other url (lets say "/Home/Do"). Now after the ajax call returns, If I click on any other element the form still submits to url1 instead of url2
Note I tried adding a "return false" statement to click event handler where the ajax call is made. But even this did not help
The ajax call is made within the jQuery dialog:
$('#myDialog').dialog({ buttons:
[
{
text: 'Next',
click: function () { HandleNext(); return false; }
}
],
title: 'Dialog-Title'
});
function HandleNext()
{
$.ajax({
type: "POST",
url: "/Home/Go",
data: dataObj,
success: function (data) {
// update html here
}
}
});
return false;
}
Anybody faced a similar issue? any solutions?
return false in the click handler is mandatory for ALL ajax requests. The web browser will visit the url otherwise. In other words: The ajax request is made first and then a regular request.
No urls can automagically be replaced with other urls. You either do it in your javascript code, or in your action/view.

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