HTML helpers in ASP.NET MVC 3 with Javascsript action - c#

I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}

With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.

You can put a <script> tag in the helper body.

How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}

Related

How to share information between partial views in JS

Two partials loaded on the same page
For example, if I hit a button in one partial then I want some value to appear in the other partial.
I want all the work to be done on the client side. I am sure I would call a method in js but I am not sure how to connect it to another js var on another partial within the same page. In other words how do I get both the partials to talk to eachother on the client side.
Once your razor view is rendered to the browser, It is just HTML markup. That means, you can use javascript to access the elements in the DOM and update the values as needed.
Keep your script in the main view which holds the 2 partial views.
$(function(){
$("#ButtonInFirstParial").click(function(e){
e.preventDefault();
$("#DivInSecondPartial").html("Updated");
});
});
Also if you declare your javascript variable in a global scope, you can access it in other places also. So if you have a variable like this in your layout page,
<body>
#RenderBody()
<script type="text/javascript">
var global_SiteUrl="Some value i want to access in all pages";
</script>
</body>
You can access it in other views (which uses the above one as the Layout), or js files which are a part of other views who has the layout value set as the above layout.

How to implement printing in ASP.Net MVC3

As part of my current task in a given list of items, user can select some of them and invoke 'Print' no the selected items.
For each selected item we need to print the details. It is similar to printing invoices of selected items in a sales system.
I have created a partial view to write each record details but I am not sure how to use it as per my requirement.
Can I call jQuery print on document.ready to achieve my requirement?
As #Levib suggested, calling partial view in my PrintView. And PrintView's document.reay function is calling window.print. But when I try to invoke 'Print', I can not see print dialogue.
This is my view,
#section Styles
{
<link rel="stylesheet" href="AdminStyle.css" type="text/css" media="all" />
<link rel="stylesheet" href="AdminPrintOrder.css" type="text/css" media="print" />
}
#foreach (var item in Model)
{
<div id="content" style="page-break-before: always">
#{Html.RenderPartial("_OrderDetailView", item);}
</div>
}
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
debugger;
window.print();
});
</script>
}
And my print invoker view is
function printInvoices(){
$.ajax({
type: 'POST',
url: '/Batch/PrintInvoices',
data: '{ "allocationId" : "' + unSelected.toString() + '"}',
contentType: "application/json; charset=utf-8",
traditional: true,
success: printedView,
error: errorInSubscribing
});
}
Do I need to handle ajax reposne to populate print dialogue.
function printedView() {
unSelected = [];
}
And controller action is
[HttpPost]
public ActionResult PrintInvoices(string allocationId)
{
var context = new BatchContext();
var orderDetails = context.GetOrderDetails(RetriveList(allocationId));
return View(orderDetails);
}
Define a print stylesheet for your page. You do this by using the #media print declaration.
What you can then do is wrap each partial view on the page that you are going to print in a div and apply the 'page-break-before: always' CSS attribute to it.
This will ensure that each partial view ends up on a different page. Call 'window.print()' on the page load and you're done!
Given the extensive questions posed in the comments for this answer, here is a more detailed description of what needs to be done:
Preparation
A stylesheet needs to be defined and applied to the page which defines what the page will look like when printed.
This can either be done by using a #media print { } declaration in an existing stylesheet, or by applying the media="print" attribute to the link tag in your page which includes the stylesheet. You appear to have done this correctly.
This stylesheet must include a page-break-before: always declaration for all elements before which you would like there to be a page break. You seem to have done this with inline styles. Personally I would have rather done this in the print stylesheet than as an inline style. This step is integral to you being able to print one item per page.
Printing
window.print() allows you as the page author to define when the page is printed. This does the same thing as CTRL + P or as clicking the print button, except you can do it from your JavaScript.
Ajax has nothing intrinsically to do with printing. Ajax is a means to asynchronously make HTTP calls from your page without changing or reloading it and updating your page as a result. If you wanted to dynamically populate your page with items to print based on user input, then you could very well do so with Ajax. If you merely want to print the page, then you don't need to use Ajax.
the navigator.**
Two important points:
window.print() prints the page that is currently onscreen. If you want to print a different page, you need to load the other page in some way shape or form (perhaps through a popup) and call window.print() on that page.
The print stylesheet defines what the printed page will look like in contrast to the onscreen version. This means that you can have a page of items and lots of other stuff, and print only the items when the user clicks the print button. You would do this by setting the display: none property in your print stylesheet on all the elements that you do not want to appear on the printed page.
About PDFs:
I have nothing against exporting pages to PDF when necessary, but as you did not specifically ask about a PDF solution, I have given you the HTML+CSS solution to your question. PDFs also take a minute to generate and load. They are great, however, when your users will want to save copies of what they are printing. If this is the case for your site I strongly recommend that you consider such a solution.
Testing:
How do you test a print stylesheet? The easiest way is to simply click the print button in Chrome which will show you a lovely preview of what your site is going to look like when it is printed.
Final word:
For now, forget about window.print() and just focus on getting your page looking like it should by applying the appropriate CSS. Write your CSS, run your page, look at the output in Chrome, modify your print stylesheet as needed... Rinse and repeat. Only once you have the page appear exactly as you want it when clicking the print button should you then look at calling the print function automatically in your JavaScript.
How I do printing in MVC:
Create a view with exactly what you want to print layed out how you want it to look
Use the Rotativa library to turn your MVC View in a pdf document.
Simple as changing your Action to look like this
public ActionResult PrintInvoice(int invoiceId)
{
return new ActionAsPdf(
"Invoice",
new { invoiceId= invoiceId })
{ FileName = "Invoice.pdf" };
}
I believe it will obey the css page-break, so if you need to only print one item per page you can use that markup to force items to new pages.
I will create a PDF to better control the layout of the page.
With jQuery I will get the selected items from the user than make an ajax call, or a simple POST, to an action method that accept a list of your items as parameter and then return a filestream containing your pdf.
There are a lot of libraries free and commercial to create a pdf both at runtime or at design time.
I personally use DevExpress and I'm happy with it.
As an opensource alternative you can consider PDFSharp

Add CSS and JS in AJAX-loaded PartialView

I found many answers about similar topics but all refers to PartialViews loaded not by AJAX where solutions are e.g. HtmlHelpers or Head section, but it doesn't work when I load PartialView by AJAX.
I wanna add CSS stylesheet and JS script inside AJAX-loaded PartialView. Now I coded it inside PartialView and it works but it's not good solution (include scripts and stylesheets inside body).
Everything should work just fine except validation. You need to tell jQuery about your new content on order to validate it.
See
ASP.Net MVC: Can you use Data Annotations / Validation with an AJAX / jQuery call?
If you are only loading the PartialView once onto the page, there should be no problem including the scripts and CSS in the body. Like Adam said if you are including a HTML Form dynamically you just have to tell jQuery about it see here ASP.Net MVC 3 client side validation with a dynamic form
However if you want to include the same PartialView multiple times on to the page and do not want to load the script multiple times. Then there are dynamic script loaders you can use that:
You can call just one from your main page, when you load the AJAX so that it is only included once
Include a check to make sure the same script is not loaded multiple times.
I didn't know that earlier that using script tag inside body is not evil. So it's not that bad I thought at first.
I implemented two functions in cssLink.js which I include in head:
/// <reference path="../jquery-1.4.4.js" />
function addCssLink(link) {
var _cssLink = '<link rel=\"stylesheet\" href=\"' + link + '\" type=\"text/css\" />';
$head = $('head');
$link = $('link[href=' + link + ']', $head);
if ($link.length == 0) {
$head.append(_cssLink);
}
}
function removeCssLink(link) {
$('head link[href=' + link + ']').remove();
}
and I use those functions within PartialViews:
<script type="text/javascript">
$(document).ready(function () {
$('#sideMenu').tabs('#content', '#content > *');
addCssLink('/Content/SideMenu.css');
});
</script>
<script type="text/javascript">
$(document).ready(function () {
removeCssLink('/Content/SideMenu.css');
});
</script>
Thank you guys for help, I think that informations about validation should be helpful for me later :)

MVC3 Layout Page, View, RenderPartial and getting script files into the Header (from the partial view)

So I have a Layout page
<head>
#RenderSection("HeaderLast", required: false)
</head>
A view
#section HeaderLast
{
<script src="#Url.Content("~/Scripts/knockout-1.2.0.js")"
type="text/javascript"></script>
}
<div id="profile-tab">
#{ Html.RenderPartial("_userProfile"); }
</div>
And a Partial view
#section HeaderLast
{
<script type="text/javascript">
alert('test');
</script>
}
<div......
I figured it couldn't be that simple. Is there a proper way to do this out of box or will this always require some kind of mediator and passing stuff around ViewData to manually make the content bubble up to the layout page?
Bounty started: The bounty will be rewarded to the best solution provided for this short coming. Should no answers be provided I will award it to #SLaks for originally answering this question.
You cannot define sections in partial views.
Instead, you can put the Javascript in ViewBag, then emit any Javascript found in ViewBag in the layout page.
#JasCav: If a partial needs its own CSS, it has no good way to get it rendered.
If that's the reason for its use, it could very well be by design.
You don't want to have a separate CSS file x partial/helper. Remember, each separate CSS file means a separate request to get it from the server, thus an additional round-trip that affects time to render your page.
Also you don't want to emit direct CSS to the HTML from the partial/helper. Instead you want it to have appropriate hooks you can use to define all the look in your site's CSS file.
You can use the same hooks you have available for CSS to activate custom JavaScript behaviors for the elements involved When JavaScript is enabled.
Finally it may be the case what you need is not a Partial View, but an extra Layout you use for some pages. With that approach you would have:
A master Layout that gets set automatically on _ViewStart like you probably has now. This defines the sections like in your sample.
A children Layout page. Here you have both the extra html, css, js you need to have for these views. This uses both #RenderBody() and #section SomeSection { } to structure your common extra layout.
Some views that point to the children layout, and others that use the default master layout.
How to get extra data to the children Layout is out of the scope of the question, but you have several options. Like having a common base for your entities; using ViewBag or calling Html.RenderAction to get that shared logic related to shared dynamic elements in the layout.
It looks like there was a similar question on SO - How to render JavaScript into MasterLayout section from partial view?.
Unfortunately, there is no possibility of declaring sections inside Partial Views. That is because RenderPartial ends up rendering totally separate view page. There is a workaround to this, though a bit ugly. But it can look better if using strongly-typed model instead of ViewData.
Basically, you need to keep track of the reference to the view which called RenderPartial and use the DefineSection method on the object passed to push data to that view.
UPDATE: There is also a blog post about dealing with RenderSection you may find useful.
Here is another approach using helper methods and templated delegate
http://blogs.msdn.com/b/marcinon/archive/2010/12/15/razor-nested-layouts-and-redefined-sections.aspx
As a follow up to my question, the JavaScript/CSS combiner/minifier tool Cassette supports this functionality to allow you to compartmentalize your JavaScript and other assets that are required for partials.
I purchased a site license and use this in all of my MVC applications now.

Methods for dynamically building JavaScript within an ASPX page?

I have a page that is referenced via a <script> tag from a page on another site. In the script src, I pass in the form I want my script to build (from a db table), and the div where the dynamically built form should go. The calling page looks something like this:
<div id="FormContainer"></div>
<script type="text/JavaScript" src="http://www.example.com/GenerateForm.aspx?FormId=1&div=FormContainer"></script>
GenerateForm.aspx contains the code that reads the QueryString parameters for the FormId, and the Div Id, and outputs JavaScript that will build the form.
My question is this. What are the different methods for "outputting" the JavaScript? Some of the JavaScript is static, and can be packaged into an external .js file and I have jQuery too. But should I add that on the GenerateForm.aspx markup page? Or should I use a ScriptManager?
And what about the dynamically built JavaScript? Currently I'm just using Response.Write() for a proof of concept, but instead, should I be doing something else? Use a Literal control on the page and set its value? Use a ScriptManager? Something else?
I know this is a verbose question, so thanks in advance!
If you want to use a seperate, referenced Javascript file, you probably want to do is use an ashx file. Basically this is just a generic handler that you'll use to write directly to the output stream without having to deal with the ASP.NET page lifecycle. If you add a basic Generic Handler (.ashx) to your site from the Add New Item dialog, the template should be enough direction, using context.Response.Write() to output your Javascript dynamically.
The ScriptManager is more useful if you want to output individual lines of Javascript to be ran at certain times, like after an event has fired. Then you can do ScriptManager.RegisterClientBlock(this, this.GetType(), "CodeBlock", "alert('Button clicked');", true); to show a client alert box after a button has been clicked, for example.
Static files should be handled just that way - statically. The server can handle the caching, and does not cause unnecessary processing if you reference the static script file directly from the script tag. However, if you need to load a static script dynamically, you could, for example, create a literal that had the <script> tag inside it. This way it uses the browser's cached version of the static file.

Categories

Resources