MVCRazorToPDF Adding page header and footer on every pages - asp.net-mvc-3

Can i make a header and footer on every pages created using MVCRazorToPDF Library
On PDFLayout.cshtml file i am making a section for the body of PDF as
<body>
#RenderBody()
</body>
And in controller i am calling the action like
return new PdfActionResult(model, (writer, document) =>
{
document.SetPageSize(new Rectangle(233, 842, 90));
document.NewPage();
});
And my View.cshtml is like a normla html page
#model PDFLAbApp.Models.PdfExample
#{
Layout = "~/Views/Shared/_PdfLayout.cshtml";
}
<h1>#Model.Heading</h1>
<p>
paragraph content repeated n times based on the model content [ its a foreach loop and page size is more than 2
</p>

Related

MVC3 Nesting Partial Views with a call to Ajax.ActionLink

I am aware of the previous two questions which talk about nesting partial views but the solutions don't work for my design (which might not be the best one but I'm unsure how to adapt it).
Background:
I collect questionnaire responses from users and store them on an sql server as xml files.
I have a partial view which loads a table with all the Responses of a given user, this partialview populates the table with things like Response date, link to xml response document, questionnaire name, link to xml questionnaire document (the questionnaire info is pulled from a different table) and an Ajax ActionLink which redirects to action which parses the two relevant xml documents to print out Question and Answer list (i.e. visualise the response to be human readable) inside the second partial view.
The first partial view contains a div underneath the table which I wish to populate onclick of the Ajax.ActionLink with the second partial view.
Problem:
The answers are rendered correctly however the partial view is loaded into a whole new page, without any styling.
The other solutions to this nesting problem use RenderPartial() however I use return PartialView()
Code:
First Partial View:
<table>
<thead>
<tr><th>headers with other info</th>
<th>Display(/th>
<tr>
</thead>
<tbody>
<tr><td>cells with other info</td>
<td>#Ajax.ActionLink("View", "DisplayResponse","HealthStatus", new { respID = item.UniqueID,qVersion=item.QuestionnaireVersion, qname = item.QuestionnaireName }, new AjaxOptions { UpdateTargetId = "responseDisp" })</td>
</tbody>
</table>
<div id="responseDisp"></div> <--- **This is the div I wish to populate, does anyone know why it's not working?**
DisplayResponse Action (without the logic for parsing the xml documents)
public ActionResult DisplayResponse(Guid respID, int qVersion, String qname) {
var allResponses = ZData.Responses;
var response = (from r in allResponses
where r.UniqueID == respID
select r
).First();
//geting an XML questionnaire document
var questionnaireDetails = ZodiacData.Questionnaires;
var questionnaire = (from q in questionnaireDetails
where q.Name == qname && q.Version == qVersion
select q
).First();
//creating XMLDocument to read the questionnaire
XmlDocument xqdoc = new XmlDocument();
xqdoc.LoadXml(questionnaire.Xml);
XmlElement qroot = xqdoc.DocumentElement;
ViewBag.qroot = qroot;
XmlDocument xrdoc = new XmlDocument();
xrdoc.LoadXml(response.Raw);
XmlElement rroot = xrdoc.DocumentElement;
ViewBag.rroot = rroot;
return PartialView("_PrintedResponse");
}
I would be grateful for any help!
In MVC3 the #AJax. helpers are rendering regular form and a tags with some extra data- attributes. To make the magic work some Javascript is needed which will use this generated data- attributes to make the necessary jQuery ajax calls.
These js functions are living in the jquery.unobtrusive-ajax.js so add this line to your layout or view and it should work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript"></script>
First, as mentioned above, you must have a reference to the jquery.unobtrusive-ajax.js file as this will get things "wired" up correctly for you.
This answer is also in response to your comment on your question about how you're passing your models to your views. You are actually making things more complicated for yourself by using the ViewBag for your model.
By using the ViewBag for your models, you will have a harder time finding/fixing/resolving issues in typo's as well as the great features of the Razor helpers. The ViewBag is a dynamic object and there are no compile time type checks. You don't need to cast your objects either (less code).
The preferred (and best practice) is to hook things up like so:
1) Your controller contains ViewModels (Strongly Typed) that are passed to the ViewModels
Controller
public ActionResult Something() {
return View();
}
public ActionResult UserView() {
UserViewModel mdoel = new UserViewModel {
Email = "me#somewherecool.com",
FirstName = "Your",
SStatuses = new List<SStatus>{
new SStatus {
ID = 0
}
}
};
return PartialView("_SomethingPartial", mdoel);
}
Index ("Something" view)
#{
ViewBag.Title = "Something";
}
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<h2>Something</h2>
#Ajax.ActionLink("Ajax Click", "UserView", new AjaxOptions { UpdateTargetId = "MyDivContainer", InsertionMode = InsertionMode.Replace })
<div id="MyDivContainer">
<!-- my content should be here -->
</div>
Partial View
#model StackModels.UserViewModel
<div class="par">
#Html.LabelFor(m => m.FirstName)
<div class="field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</div>

MVC3 Drop Down or ListBox with dynamic check boxes

I have an MVC3 C#.Net web app. I have a requirement to display a list of check boxes (either in a drop down or a List Box) dynamically based on a table in our db. The table can contain 1:500 entries. I then need to pass the selected check boxes to the Controller in order to perform an action on each selection. Any ideas on an implementation?
There are many ways to go about this but here is a general demo.
You can pass a list of the checkbox values and descriptions either on the Model (as this example does), ViewData[""] dictionary or ViewBag (MVC3+).
Then in your view loop through them and add them to your form using the name="chxBxGroupName" to group them.
Now create a controller action to post to that takes a List of the value type (in this example int) with the parameter naming matching the name="chxBxGroupName".
It will post a list of checked values.
The post page will just print out:
123
456
// This is your landing page. It gathers the data to display to the user as checkboxes.
public ViewResult MyPageWithTheCheckboxes()
{
// For example: Assume a Dictionary with the checkbox value and description
// Replace with DB call, etc.
return View(new Dictionary<int, string> { { 123, "Foo" }, { 456, "Bar" } });
}
<%# Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<Dictionary<int,string>>" %>
<!-- Rest of HTML page... -->
<form id="frm1" action="<%=Url.Action("MyPost")%>" method="post">
<% foreach (var item in Model) { %>
<input type="checkbox" id="chxBx<%=item.Key%>" name="chxBxGroupName" value="<%=item.Key%>"/>
<label for="chxBx<%=item.Key%>"><%=item.Value%></label>
<br/><br/>
<% } %>
<input type="submit" value="Go!"/>
</form>
<!-- Rest of HTML page... -->
public ContentResult MyPost(List<int> chxBxGroupName)
{
return Content(string.Join(Environment.NewLine, chxBxGroupName ?? new List<int>()), "text/plain");
}
the answer provided by Jay accomplishes exactly what you need. If you want to put the items in a list you can do it by surrounding the markup with a div control lie below
<div style="height:40px;overflow:auto;">
<% foreach (var item in Model) { %>
<input type="checkbox" id="chxBx<%=item.Key%>" name="chxBxGroupName" value="<%=item.Key% >"/>
<label for="chxBx<%=item.Key%>"><%=item.Value%></label>
<br/><br/>
<% } %>
</div>
unfortunately you cant have checkboxes in a <select />, but if you really wanted it to look like a select list you could add some JQuery that processes onclick of a textbox and shows the div. This obviously would require some jQuery and might not be worth it

MVC Ajax action Link copies itself and appends, how do i fix

I am using ordered list design to to make my twitter app to view the tweets. Every Time I call the ajax insert, it puts puts another copy of the ajax link on the page . I am just trying to get the next set of tweets from the controller and inserting them so it lines up. I have tried moving the tags around and but the additional ajax buttons keep showing up.
Thinking it was a css problem i stripped it all out. Wasnt the issue. I will have to reformat my list again to put the closing and openning tags before and after the code block.
I just tried to putting it in a partial view and I put the ajax code in the layout.
Ajax Action Link
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
Partial View
<div id="TweetBox">
<div class="TwitterMessageBox">
<ol>
<li class="TweetLineBody">
#foreach (var item in Model)
{
#Html.Hidden(item.StatusId, item.StatusId)
<div class="TwitProfileImage">
<img src=#Url.Content(item.ImageUrl) alt="#item.ScreenName" />
</div>
<div class="TwitRealName">
#item.User
</div>
<div class="TwitNickName">
#MvcHtmlString.Create(#Html.Namify(#item.ScreenName))
</div>
<div class="TweetText">
#MvcHtmlString.Create(#item.Tweet)</div>
<div class="TweetTime">
#Html.RelativeDate(#item.Created)</div>
<div class="TweetRating">
Rating</div>
}
</li>
</ol>
</div>
</div>
The Controller is just a basic Enumerable List on the Home/ Index
This is the behavior
Lets say you have an ajax call that gets data from a controller action. It inserts before on a targetid thats a div id.
The initial view is perfect
AJAX UPDATE HTML LINK // You click it to get the controller invoke the ajax and get the data
Tweet 1
Tweet 2
etc = its perfect and aligned
You click the Ajax action link in your webpage, It goes out and gets the data but adds a second like like this
AJAX UPDATE HTML LINK
AJAX UPDATE HTML LINK
Tweet 1
Tweet 2 // alignment is still perfect but you have the 2nd ajax links
Now click the ajax link a 3rd time
// alignment is still perfect but you have the 2nd ajax link at top and one sandwiched
AJAX UPDATE HTML LINK
AJAX UPDATE HTML LINK
Tweet 1
Tweet 2
// alignment is still perfect but you have the 2nd ajax link at top and one sandwiched
Plus the Tweets results
AJAX UPDATE HTML LINK
Tweet 1
Tweet 2 // alignment is still perfect but you have the 2nd ajax links at the top and a 3rd List is inserted betweet 2/3
Controller Code per request:
public class HomeController : Controller
{
//
// GET: /Home/
private TwitterContext twitterCtx;
public ActionResult Index()
{
twitterCtx = new TwitterContext();
List<TweetViewModel> friendTweets = (from tweet in twitterCtx.Status
where tweet.Type == StatusType.Public
select new TweetViewModel
{
ImageUrl = tweet.User.ProfileImageUrl,
UserId = tweet.UserID,
User = tweet.User.Name,
ScreenName = tweet.User.Identifier.ScreenName,
StatusId = tweet.StatusID,
Tweet = HomeController.AddWebAndTwitterLinks(tweet.Text),
Created = tweet.CreatedAt
})
.ToList();
return View(friendTweets);
}
My Desired Behavior is 1 ajax link to call the controller and the data inserts
Without seeing all the code, I can only assume you don't have your views sorted out. Your controller appears to be returning the full Index view. If you put your tweet box into a partial view, your ajax action needs to be returning that partial view.

ASP.NET MVC Parial views and layouts in Razor

Is it possible for a partial view to have a layout so that whenever the partial is rendered - it is rendered with its own layout ?
Yes you can have a layout for a partial, just make sure your layout is not defining the header and the body sections of your html (because it's for a partial).
here is a sample:
_partialViewLayout.cshtml
<div class="partial-view-container">
#RenderSection("partialViewContent", true)
</div>
partialView.cshtml
#{
Layout = "~/_partialViewLayout.cshtml";
}
#section partialViewContent {
<div></div>
}

How do I render the various parts (like tags) of a blog post in Orchard CMS?

I'm trying to render the list of blog posts in this layout:
[first post - special summary]
[second post][third post][fourth post]
[pager]
I'm trying to render the first post myself and then loop over the remaining items to render them using the blog post summary template.
A number of questions here:
Is this a good way to pull off the
layout I'm trying to achieve or
should I start looking into creating
a module?
Should I create a summary
template for my special first post
rendering and how would I go about
that?
If I continue down the same
path how do I render parts like tags
and the postdate?
I have this so far in my theme: Parts.Blogs.BlogPost.List-url-blog.cshtml
#using Orchard.Blogs.Extensions;
#using Orchard.Blogs.Models;
#using Orchard.ContentManagement;
#using Orchard.Utility.Extensions;
#{
IEnumerable<dynamic> blogPosts = Model.ContentItems;
Model.ContentItems.Classes.Add("content-items");
Model.ContentItems.Classes.Add("blog-posts");
var firstPost = blogPosts.FirstOrDefault();
//BlogPart blog = (BlogPart)firstPost.Get(typeof(BlogPart));
}
<h1>#firstPost.Title</h1>
by <span>#firstPost.ContentItem.CommonPart.Owner.NormalizedUserName</span>
#* How do i render tags using the tags part template? *#
#Display(firstPost.Tags)
#Display(firstPost.Parts_Tags_ShowTags)
#Display(firstPost.TagsPart)
#Display(firstPost.ContentItem.TagsPart)
#Display(firstPost.ContentItem.TagsPart.ContentItem)
#* none of the above work *#
<hr />
<ul class="content-items">
#foreach (var post in blogPosts.Skip(1))
{
<li class="content-item-summary">
#Display(post)
</li>
}
</ul>
Bonus points - Why can't I do something like this:
#Display(blogPosts.Skip(1))
but I can do
#Display(blogPosts)
Oh, hi. Try this:
#using Orchard.Blogs.Extensions;
#using Orchard.Blogs.Models;
#using Orchard.ContentManagement;
#using Orchard.Utility.Extensions;
#{
IEnumerable<dynamic> blogPosts = Model.ContentItems;
Model.ContentItems.Classes.Add("content-items");
Model.ContentItems.Classes.Add("blog-posts");
var firstPost = blogPosts.FirstOrDefault();
var otherPosts = blogPosts.Skip(1).ToList();
}
<h1>#firstPost.Title</h1>
by <span>#firstPost.ContentItem.CommonPart.Owner.NormalizedUserName</span>
#Display(New.MyTagShape(Tags: firstPost.ContentItem.TagsPart.CurrentTags))
<hr />
#Display(New.List().AddRange(otherPosts))
And then this is the code for MyTagShape.cshtml:
Here are your tags:
<ul>
#foreach (var tag in Model.Tags) {
<li>#tag.TagName</li>
}
</ul>
Works on my machine.
But as I was saying on the forums, you might want to customize the summary templates rather than the whole list.
Edit: here is how you would create a different template for the first item: http://weblogs.asp.net/bleroy/archive/2011/05/23/orchard-list-customization-first-item-template.aspx

Resources