Open Rotativa print dialog automatically - asp.net-mvc

I am using Rotativa to generate a PDF of a view with the intention of printing it.
I have the following code
public ActionResult PrintTicket(string tempTickID)
{
//var tick = ctx.vw_printTicket.Where(e => e.noTicket == tempTickID).FirstOrDefault();
// return View(tick);
var report = new ActionAsPdf("PrepareTicket", new { tempTickID = tempTickID });
return report;
}
ActionAsPdf allows me to open the "PrepareTicket" view as a pdf and then I can print.
Problem
The problem for me is this, The pdf takes over my entire page and while I can print I don't have access to my program's menus anymore cause it's now a PDF view.
Questions
Is it possible that I call the print dialog automatically instead of showing the pdf?
I think will work for my situation.
Regards

Hi I have tried to create a sample which will solve your issue.
Model
public class Ticketinfo
{
public string name { get; set; }
public int quantity { get; set; }
}
Created a Controller which has 3 Action Method
public class GenerateController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult PrintTicket(string tempTickID)
{
return new ActionAsPdf("RotativaPartialViewAsPdf", new { tempTickID = tempTickID });
}
public ActionResult RotativaPartialViewAsPdf(string tempTickID)
{
Ticketinfo Ticketinfo = new Ticketinfo()
{
name = "Demo",
quantity = 5
};
return PartialView("_RotativaPartialViewAsPdfl", Ticketinfo);
}
}
Partial View
#model WebApplication6.Models.Ticketinfo
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<table class="table">
<tr class="info">
<td>Lot</td>
<td>Name</td>
<td>Quantity</td>
</tr>
<tr class="success">
<td>#Model.name</td>
<td>#Model.quantity</td>
</tr>
</table>
</div>
</body>
</html>
Index View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<iframe src="#Url.Action("PrintTicket", "Generate", new {tempTickID = "1"})"
width="800px" height="600px">
</iframe>
</div>
</body>
</html>
Output

Related

cant pass current Date & Time using Viewdata in mvc

i am new in MVC.I try to pass Current Date & Time by using Viewdata.But it does not get my code is here
namespace FirstHelloWorldProjct.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public ActionResult Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}
}
}
And my View Code here
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
This is Hello World...<br/>
The Current Date and time is <%= ViewData["CurrentTime"]%>
</div>
</body>
</html>
And output is here
This is Hello World...
The Current Date and time is <%= ViewData["CurrentTime"]%>
I think In Asp.net MVC we use Razor syntax as metion below.
you need to use #ViewData["CurrentTime"] instead of <%= ViewData["CurrentTime"]%>

Error of populating menu items permenantly and unwantedly in each postback in MVC

I have a problem. In order to make it understandable, I want to denote my layout. layout is as follows:
Menu side is implemented by NavController. Here is the content of the NavController:
public class NavController : Controller
{
private IProductRepository repository;
public NavController(IProductRepository repo) {
repository = repo;
}
[ChildActionOnly]
public PartialViewResult Menu(string category = null)
{
ViewBag.SelectedCategory = category;
//IEnumerable<string> categories = repository.Products
//.Select(x => x.ProductCategory)
//.Distinct()
//.OrderBy(x => x);
IEnumerable<string> categories = Actions.GetirTumAksiyonları();
return PartialView(categories);
}
}
At the Menu action method, some strings populated and become visible at the Menu side.
There are many controllers defined in my project that manipulates the Content of the project, and they have buttons that post back to server. Whenever I click at one of these buttons, menu strings permenantly populated. Here is my _Layout.cs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<link href="~/Content/Site.css" type="text/css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
</head>
<body>
<div id="header">
<div class="title">Lojman Bilgi Sistemi</div>
</div>
<div id="categories">
#{ Html.RenderAction("Menu", "Nav"); }
</div>
<div id="content">
#RenderBody()
</div>
How can I overcome the issue? thanks in advance.
You can write your Menu method this way. Cheers :)
[ChildActionOnly]
public PartialViewResult Menu(string category = null)
{
// Logic
}

How to show entered order no and selected product name and id

i am new in mvc. so could not figure out what to add in code to show entered order no and selected product name and id.
here is full code and dotnetfiddle url https://dotnetfiddle.net/6vn2GO
Model code
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class OrderViewModel
{
[Display(Name = "Order number")]
public int? OrderNumber { set; get; }
[Display(Name = "Product")]
[Required(ErrorMessage = "Please select a product")]
public int SelectedProductId { set; get;}
public SelectList ProductList { get; set; }
}
public class Product
{
public int ID { set; get; }
public string Name { set; get; }
}
public static class Repository
{
public static IEnumerable<Product> FetchProducts()
{
return new List<Product>()
{
new Product(){ ID = 1, Name = "Ketchup" },
new Product(){ ID = 2, Name = "Mustard" },
new Product(){ ID = 3, Name = "Relish" }
};
}
}
}
Controller code
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
OrderViewModel model = new OrderViewModel();
model.OrderNumber=null;
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(OrderViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
// but for testing purposes
ConfigureViewModel(model);
return View(model);
}
private void ConfigureViewModel(OrderViewModel model)
{
IEnumerable<Product> products = Repository.FetchProducts();
model.ProductList = new SelectList(products, "ID", "Name");
}
}
}
View.cshtml code
#model HelloWorldMvcApp.OrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(m => m.OrderNumber)
#Html.TextBoxFor(m => m.OrderNumber, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.OrderNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.SelectedProductId)
#Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {#class="form-control"})
#Html.ValidationMessageFor(m => m.SelectedProductId)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
please tell me what code i need to add in view html to show entered order no and selected product name and id. thanks
You could set the value of your order number on the [HttpPost] Action method and check if it's null on the view side and show/hide stuff accordingly.
Another (probably better) alternative would be to just create a new view and return that when the model state is valid. To get the order number, you'll need to fetch the inserted ID from the database and pass that to the view.
Edit to show some code:
Controller Code:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
OrderViewModel model = new OrderViewModel();
model.OrderNumber=null;
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(OrderViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
// but for testing purposes
ConfigureViewModel(model);
// you'll need to figure out how you're generating your
// order numbers
//
model.OrderNumber = 1; // just set this statically for now for POC
return View(model);
}
private void ConfigureViewModel(OrderViewModel model)
{
IEnumerable<Product> products = Repository.FetchProducts();
model.ProductList = new SelectList(products, "ID", "Name");
}
}
}
View Code:
#model HelloWorldMvcApp.OrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
#{
if(Model.OrderNumber == null)
{
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(m => m.OrderNumber)
#Html.TextBoxFor(m => m.OrderNumber, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.OrderNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.SelectedProductId)
#Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {#class="form-control"})
#Html.ValidationMessageFor(m => m.SelectedProductId)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
</div>
} else {
<div>show your confirmation stuff here</div>
}
}
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
that will reuse the same view, though as I said, I'd recommend using a different view.

how build dynamic layout mvc 4?

how return razor code for layout of view instead of master page name
for example instead of
return View("Index", "_Layout");
use this code
return View("Index", #"
#using System.Diagnostics
#using iaumahallat.Helper
<!DOCTYPE html>
<html lang="en">
<head>
<title>#ViewBag.SiteTitle - #ViewBag.Title</title>
<meta name="description" content="#ViewBag.MetaDescription">
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
");
One way is to use RazorEngine and parse the razor source code, then get the corresponding Html String to display it on the view or layout-
Razor.SetTemplateBase(typeof(HtmlTemplateBase<>));
string template =
#"<html>
<head>
<title>Hello #Model.Name</title>
</head>
<body>
Email: #Html.TextBoxFor(m => m.Email)
</body>
</html>";
var model = new PageModel { Name = "World", Email = "someone#somewhere.com" };
string result = Razor.Parse(template, model);
Then use result in the page of your interest.

MVC 4 Updating a view with a controller action

I'm new to MVC. I want to be able to change a button/divs/textboxes text when a view's button is clicked. I found a tutorial online that showed me the following but when I click the button I'm getting redirected to another page. That page shows the text instead. I haven't touched the default Global.aspx
View
#using (Ajax.BeginForm("ExamineTextBox", new AjaxOptions { UpdateTargetId = "result" }))
{
#Html.TextBox("textBox1")
<input type="submit" value="Button" />
<span id="result" />
}
Controller
public string ExamineTextBox(string textBox1)
{
if (textBox1 != "Initial Data")
{
return "This text is MVC different from before!";
}
return String.Empty;
}
Make sure you have included the jquery.unobtrusive-ajax.js script to your page.
If you are using the default bundles (take a look at ~/App_Start/BundleConfig.cs - you will see a jqueryval bundle defined which combines and minifies all ~/Scripts/jquery.unobtrusive* and "~/Scripts/jquery.validate*" files):
#Scripts.Render("~/bundles/jqueryval")
and if not using bundles you could include only this script individually:
<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>
It is this script that is required for Ajax.* helpers to work. As it name indicates it unobtrusively AJAXifies them. It depends on jQuery so make sure you have that one included as well.
Side note: In ASP.NET controller actions should return ActionResults, not strings:
public ActionResult ExamineTextBox(string textBox1)
{
if (textBox1 != "Initial Data")
{
return Content("This text is MVC different from before!");
}
return Content(String.Empty);
}
Here's how your full view code might look:
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
#using (Ajax.BeginForm("ExamineTextBox", new AjaxOptions { UpdateTargetId = "result" }))
{
#Html.TextBox("textBox1", "Initial Data")
<input type="submit" value="Button" />
<span id="result" />
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
</body>
</html>
and the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ExamineTextBox(string textBox1)
{
if (textBox1 != "Initial Data")
{
return Content("This text is MVC different from before!");
}
return Content(String.Empty);
}
}

Resources