Posts

Showing posts with the label MVC

Build an ActionLink with a Value from the Page

Normally I would use an Html.BeginForm and wrap my link inside it to force it to the controller to handle any variables, but every so often you may need to add a link on the page which is populated with a variable from a textbox and you choose not to post back to the controller. In this example I want to pass an account number in my ActionLink So I start by adding the textbox on the page  Enter Account Number: @Html.TextBox("account") And the Actionlink (using some bootstrap formatting)   @Html.ActionLink("View", "Customer", null, new { id = "View", @class="btn btn-danger" }) Then I handle the click event in script on the page <script>     $(function () {         $('#View').click(function () {             var fran = $('#account').val();             this.href = this.href + '?id=' + encodeURIComponent(fran);         });     }); <...

Pivot Data and Roll up 12 months of Summaries

Image
The need was for a report that rolled up sales by item by month for the year on the MVC Razor page.  Here is how I did it. First I created a Model that looked like this   public  class DTO_SkuReport     {         public string SKU { get; set; }         public int Month { get; set; }         [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]         public decimal linetotal { get; set; }         public decimal JanTotal { get; set; }         public decimal FebTotal { get; set; }         public decimal MarTotal { get; set; }         public decimal AprTotal { get; set; }         public decimal MayTotal { get; set; }         public decimal JunTotal { get; set; }         public decimal JulTotal { get; set; } ...

The Beautiful Razor WebGrid

The webgrid is truly a work of art.  The fastest way to show results of a query in a friendly, sortable, easily formattable fashion. Conditionally formatting our data can sometimes offer struggles so here are a couple of tips. Have a pesky nullable date column? You can add something like this inside your grid - here I am working with both a status and a nullable date.  So if the status equals "NA"  (I set that in my query if the step wasn't relevant), I am returning a black box into the cell otherwise i am returning the sew date (item.Sew) which can be nullable - here I am returning an empty cell if null or a nicely formatted date if not. IF STATEMENT IN GRID  ,grid.Column(header:"Sew", format: (item) =&gt;                 {                     if (item.SewStatus == "NA")                     { return Html.Raw(s...

Binding a Dropdownlist on a blank form to a Model using a dictionary

In my Models folder I have a class for United States that looks like this:  public class UnitedStates     {           public static readonly IDictionary Cust_States = new Dictionary<string, object>                 {{"AL", "AL"},{"AK", "AK"},{"AZ", "AZ"},{"AR", "AR"},{"CA", "CA"},{"CO", "CO"},                 {"CT", "CT"},{"DE", "DE"},{"FL", "FL"},{"GA", "GA"},{"HI", "HI"},{"ID", "ID"},                 {"IL", "IL"},{"IN", "IN"},{"IA", "IA"},{"KS", "KS"},{"KY", "KY"},{"LA", "LA"},                 {"ME", "ME"},{"MD", "MD"},{"MA", "MA"},{"MI", "MI...

Posting out to 3rd party API

Example of taking data in the form of a Model from your site and sending it out somewhere else and getting back a httpresponsemessage. [HttpPost]   public HttpResponseMessage Post(Appt_Model_DTO  appt)         { >>>>You could eliminate this portion   if (ModelState.IsValid)             { //not necessary but you can run some checks to make sure the data is good //that the model is valid and there is not  //you posted this data from your MVC site to your API Controller //Now we are going to send it off to a third party site                 if (appt.ID == null) {                     appt.ID = my_provider.getRecordwithSameIdentity(appt.AccountCode);                 }                 appt.StartDateTime = DateTime.Now;   ...

Simple Breadcrumbs in Razor

If you wish to add Breadcrumb navigation to your site. This is a quick and easy way to do it.  This is only effective if every controller has an Index view and if you are passing route variables such as 'acct=xxx' then this will not accommodate those values so you have to make sure your app is able to manage without the variables and offer another option. @Html.ActionLink("Home", "Index", "Home") @if(ViewContext.RouteData.Values["controller"].ToString() != "Home") { @Html.ActionLink(ViewContext.RouteData.Values["controller"].ToString(), "Index", ViewContext.RouteData.Values["controller"].ToString()) } @if(ViewContext.RouteData.Values["action"].ToString() != "Index"){     @Html.ActionLink(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString()...

PDF from MVC Razor - with heading

Image
Today I was tasked with creating a PDF from a report that had two queries - a header section and detail section. After looking at all the viable options I was tempted by iTextSharp but was faced with the challenge of implementing it in razor.  I then came across this nifty dll written specifically for that purpose and it utilizes iTextSharp to do it. RazorPDF  was the answer.  Al Nyveldt did an excellent job with it and includes a github download with great samples.  The one challenge he didn't cover was my example of two queries to make a more comprehensive report. As shown in the example (screenshot of my pdf generated using this tool) I have header information as well as additional data laid out in a table. To accomplish this I created a ViewModel in my Data project with a simple class that incorporated two references.  One to the header data and one to the Zipcode detail.     public class Fran_Zip_ViewModel     {   ...

C#, MVC Tips and Stuff

A list of things that I have found handy to know... Tip #1 Boolean Enum Comparison Not to return an enum value from say an abbreviation to a long string but just to determine if your value is a valid value in the enum list.  So you have your Enums declared in a base class or some other class something like this:  public enum MyCustomEnumGroup     {         ABC,         MQP,         RAD,         STY     } Then wherever you need  to check your string to see if the string you are passing in is in the Enum Group call it as shown below, this returns a boolean based on the match to the enumgroup.   if (Enum.IsDefined(typeof(MyCustomEnumGroup),mystringtopassin))

Wrapping my head around MVC - one page, two views

I am really loving MVC, only really immersed in it for a couple of months but it is all coming together for me lately.  The most difficult challenge I faced in the beginning was generating a mixed context view, by that I mean something more akin to a normal web page. Maybe some header information at top and a grid of data below.  At first it was really easy to get something like a customers orders in the grid but how to display another grid of customer address information on the same page.  So to accomplish this lets say that you have a class that has the orders info. Orders.cs customerid orderid balance description And you have a customer class Customers.cs customerid customername streetaddress Cust_ordersDTO .cs CustomerID orderid balance description CustomerName StreetAddress public List< Cust_orders > AddressList { get; set; } public List< Cust_orders > OrderList { get; set; } So you will need to make a new class that has all properti...

How to get Commas in your razor Html.TextBoxFor

There are so many ways to do this ... but depending on circumstances they don't always work.  The simplest way is to apply the format directly on the Textbox like this:   @Html.TextBoxFor(model => item.Population, "{0:N0}", new {style = "width: 100px;"})

Cannot Convert Int to String - MVC Dropdownlist Nightmare

So I struggled with this simple code for binding a dropdownlist IEnumerable items = db.SiteMenus               .Select(c => new SelectListItem  {  Value = c.MenuID,  Text = c.MenuName               });                  ViewBag.SiteMenuItems = items;               return View();                .Select(c => new SelectListItem   {              Value = c.MenuID,                                Text = c.MenuName               });              ViewBag.SiteMenuItems = items; return View();             list.Add(new SelectListItem { Text = "-Select Catego...