asp.net mvc partialview #Ajax.ActionLink doesn't work - ajax

I have a view page
my view page
<div id="beReplaced">
#Ajax.ActionLink("please click on me to bring the partial view",
"PatrialViewToBeCalled",
new AjaxOptions()
{UpdateTargetId = "beReplaced",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod="Get",
LoadingElementId = "prgress" })
</div>
i have a Controller
public PartialViewResult PatrialViewToBeCalled()
{
var customer = db.Customers.First();
return PartialView("PartialViewThatMustBeShow",customer);
}
but when i click on the generated link it brings me to a new page instead of
replacing or appending the partial view to the div tag.
What's the problem?

It could have been that you were missing the:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
In the main view. This tells the main view to recognize the ajax helper.

I found the solution. The problem was due to the corrupted unobtrusive-ajax.min.js file.

If you have jQuery loaded into your page, why not use the simple jquery get / load method to get the partial view ?
<div id="beReplaced">
please click on me to bring the partial view
</div>
Javascript
$("#lnk1").click(function(){
$.get('/controller/PatrialViewToBeCalled', function(data) {
$('#beReplaced').html(data);
});
});

If you are working with ASP .NET MVC 4 make sure that
#Scripts.Render("~/bundles/jquery")
is in the end of the body tag as well.
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
</html>

I've just been working on it for too long, thinking it did not work. Viewing the page source didn't show anything either.
Eventually, I found out it actually did work when I saw the successful requests in the console of Firebug. It only was showing it off screen. In the HTML tab of Firebug I finally found the output, even though it does not show up in the page source.

Related

How to Return a View from a Controller to an iFrame

I am new to MVC 3 and have come accross the following scenario:
First let me explain how I have setup my application:
All post backs to the server use jquery ajax which which return a view from the controller that either appended or prepended or replace a targeted div.
The Scenario:
I have come to a point where I would like to upload images but unfortunately because of the jquery ajax posting I cannot get the values for an html in C# Request.Files. I know there are plugins out there to help out with this but I would like to do this myself so I have created an <iframe> which i then use a bit of javascript and post the form targeted to the iframe (old classic way of doing things):
function UploadImg(SACTION) {
alert(SACTION);
validatorform.action = SACTION;
validatorform.target = "fraImage";
validatorform.method = "POST";
validatorform.submit();
}
the SACTION parameter looks like this #Url.Action("UploadFile", "Response"). This all works well as it hits the controllers action method and I can then save the image:
[HttpPost]
public ActionResult UploadFile(string ArticleID)
{
ViewBag.PreviewImage = cFileUploads.UploadFile(ArticleID, Request.Files[0]);
return View("ImagePreview");
}
I would now like to return a view to the iframe (simply to preview the image and then do a couple of other things but this is besides the point)
The View for previewing the Image:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="">
<img alt="" src="#ViewBag.PreviewImage" />
</form>
</body>
</html>
The Problem:
Unfortunately when I return the View (ImagePreview.cshtml) in C# the whole page is refreshed, all I want is for the iFrame to be refreshed. How should I return the view from the controller?
Fiqured out the problem, I had a bit of javascript that was replacing the contents of a div that the iframe was sitting in ... (slap on my forehead). All working perfectly now :)
Will leave this question here just incase ..

MVC 3 - Nested layouts - sections don't render in Areas

Problem:
Given this nested layout structure:
~/Views/Shared/_layoutBase.cshtml
~/Views/Shared/_layout.cshtml
Where _layoutBase.cshtml is the layout for _layout.cshtml.
Any sections defined in the layout files render their content fine in pages under ~/Views/...
However, for views in an area, the sections are never rendered.
Setup:
_layoutBase:
<script type="text/javascript">
#RenderSection("footerScripts", false)
</script>
</body>
</html>
_layout.cshtml:
#section footerScripts{
#RenderSection("footerScripts", false)
}
"content" view:
#section footerScripts{
$(function () {
SetFocusOnForm("CaptchaCode", "NextButton");
});
}
The content of section footerScripts never gets rendered in a view in an area. It does get rendered in a view that is under the ~/Views folder.
Area _ViewStart.cshtml:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Question:
Can you see anything wrong?!
I am unable to reproduce the problem. Here's my setup and steps I did.
Create a new ASP.NET MVC 3 application using the Internet Application Template
Add ~/Views/Shared/_LayoutBase.cshtml:
<!DOCTYPE html>
<html>
<body>
#RenderBody()
<script type="text/javascript">
#RenderSection("footerScripts", false)
</script>
</body>
</html>
Replace the contents of ~/Views/Shared/_Layout.cshtml with this:
#{
Layout = "~/Views/Shared/_LayoutBase.cshtml";
}
#section footerScripts{
#RenderSection("footerScripts", false)
}
#RenderBody()
Right click on the project and add an Admin area
Add a TestController to this admin area and add a corresponding ~/Areas/Admin/Views/Test/Index.cshtml view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#section footerScripts{
alert('ok');
}
Run the application and navigate to /admin/test/index
The alert is shown
The Reason Why:
I have got up this morning and saw the problem straight away:
I had the #section blocks in a Partial View. In MVC 3, that WON'T work!!
ARGH!
I really appreciate Darin's effort, that effectively provided proof that sections do work in Areas as expected. But the real cause was this.
I forgot they were in a Partial View, because I have a mvc 3 wizard that uses partial views for steps. It works so well and consistently, using ajax if javascript is available, that you forget what you are doing.
Please give Darin a vote, but this is the real answer.

Reloading everything but one div on a web page

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

Using Jquery in Controller Page-ASP.NET MVC-3

Could any one give an example, how to use Jquery in Controller Page. MVC3 -ASP.NET(How To put various tags like )
I want to show a simple alert before rendering a view in Controller.
Thank you.
Hari Gillala
Normally scripts are part of the views. Controllers shouldn't be tied to javascript. So inside a view you use the <script> tag where you put javascript. So for example if you wanted to show an alert just before rendering a view you could put the following in the <head> section of this view:
<script type="text/javascript">
alert('simple alert');
</script>
As far as jQuery is concerned, it usually is used to manipulate the DOM so you would wrap all DOM manipulation functions in a document.ready (unless you include this script tag at the end, just before closing the <body>):
<script type="text/javascript">
$(function() {
// ... put your jQuery code here
});
</script>
If you are talking about rendering partial views with AJAX that's another matter. You could have a link on some page that is pointing to a controller action:
#Html.ActionLink("click me", "someAction", null, new { id = "mylink" })
and a div container somewhere on the page:
<div id="result"></div>
Now you could unobtrusively AJAXify this link and inject the resulting HTML into the div:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href, function() {
alert('AJAX request finished => displaying results in the div');
});
return false;
});
});

JQuery for Push-down form

Is there a JQuery plugin that allows me to 'unhide' a form by after clicking a link? Like I have an invite link that can take me to a one text field form for an email address but I want this form to just drop down (pushing the rest of the content down also) and shows the form to submit the email. If you guys can think of a JQuery plugin that lets me do this, please let me know
Edit:
So I did this
<div class='add-link'>
<div id='invite_link'><a href=''>Invite User</a></div>
<div id='invitation_form'>
<form>
<input type='text'/>
</form>
</div>
</div>
and my jquery looks like
<script type="text/javascript">
$(function()
{
$("table").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']});
$('#invitation_form').hide();
}
);
$('#invite_link').click(function() {
$('#invitation_form').slideDown();
});
Do you guys see any error that causes the form not to slide down. It hides the form when the page loads but when I click the link it is not sliding down.
$('a.mylink').click(function() {
$('#MyForm').slideDown();
});
I don't think you need a jQuery plugin for this. The base jQuery library should be sufficient.
$('#showFormLink').click(function () {
$('#form').slideDown();
});
If you're looking for animation, that's possible as well by passing in a duration argument to slideDown.
Take a look at the jQuery show documentation.

Resources