.

This class/ActionResult will display an XML file in the webbrowser (standard IE XML file viewing)

public class XmlResult : ActionResult
{
    public XmlResult(string text)
    {
        Text = text;
    }

    public string Text { private get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        HttpContextBase httpContextBase = context.HttpContext;
        httpContextBase.Response.Buffer = true;
        httpContextBase.Response.Clear();

        string fileName = DateTime.Now.ToString("ddmmyyyyhhss") + ".xml";
        //httpContextBase.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        httpContextBase.Response.ContentType = "text/xml";

        using (var writer = new StringWriter())
        {
            writer.Write(Text);
            httpContextBase.Response.Write(writer);
        }
    }
}

usage:

[OutputCache(Duration = 0)]
public ActionResult DisplayXmlContent(string xml)
{
    return new XmlResult(xml);
}

writing HtmlExtensions

The following is an example of how to write a Html Extension

This particular example is to build a foreach loop for Knockout.

the Html Extension:

public static class HtmlExtensions
{
    public static KoForeach<TModel, TProperty> KoForeach<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
    {
        return new KoForeach<TModel, TProperty>(htmlHelper, htmlAttributes);
    }
}

The tag class (seperate class so that on disposal, it will fire the closing tag)

public class KoForeach<TModel, TProperty> : IDisposable
{
    private readonly HtmlHelper<TModel> _helper;

    public KoForeach(HtmlHelper<TModel> helper, object htmlAttributes = null)
    {
        _helper = helper;
        var attrs = new StringBuilder();

        if (htmlAttributes != null)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
            {
                attrs.Append(string.Format(" {0}={1}", property.Name, property.GetValue(htmlAttributes)));
            }
        }

        _helper.ViewContext.Writer.Write(string.Format("<!-- ko foreach: {0} -->", "names"));
    }

    public IHtmlString Item(string item)
    {
        return new HtmlString(string.Format("<li>{0}</li>", item));
    }

    public void Dispose()
    {
        _helper.ViewContext.Writer.Write("<!-- /ko -->");
    }
}

usage:

@using (Html.KoForeach(myvm => myvm.names))
{
    <input type="text" data-bind="value: $data"/>
}

script:

<script type="text/javascript">
    var viewModelName = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
//this relies on: @*<script src="~/Scripts/knockout.mapping-latest.js"></script>*@
    console.log(viewModel.names());
    ko.applyBindings(viewModel);
</script>

[resolved] A potentially dangerous Request.Form value was detected from the client

When posting to a MVC controller, I get the following error:
A potentially dangerous Request.Form value was detected from the client

To get around this, disable validation by adding this attribute to the controller method you’re posting to:
[ValidateInput(false)]

Creating a cascade dropdown in MVC & C# (version 2)

Now, let’s follow the steps.
Step 1
At very first, we need a model class that defines properties for storing data.
    public class ApplicationForm
    {
        public string Name { get; set; }
        public string State { get; set; }
        public string District { get; set; }
    }
Step 2
Now, we need an initial controller that will return an Index view by packing list of states in ViewBag.StateName.
    public ActionResult Index()
    {
        List<SelectListItem> state = new List<SelectListItem>();
        state.Add(new SelectListItem { Text = “Bihar”, Value = “Bihar” });
        state.Add(new SelectListItem { Text = “Jharkhand”, Value = “Jharkhand” });
        ViewBag.StateName = new SelectList(state, “Value”, “Text”);
        return View();
    }
In above controller we have a List<SelectListItem> containing states attached to ViewBag.StateName. We could get list of states form database using Linq query or something and pack it to ViewBag.StateName, well let’s go with in-memory data.
Step 3
Once we have controller we can add its view and start creating a Razor form.
@Html.ValidationSummary(“Please correct the errors and try again.”)
@using (Html.BeginForm())
{
    <fieldset>
        <legend>DropDownList</legend>
        @Html.Label(“Name”)
        @Html.TextBox(“Name”)
        @Html.ValidationMessage(“Name”, “*”)
        @Html.Label(“State”)
        @Html.DropDownList(“State”, ViewBag.StateName as SelectList, “Select a State”, new { id = “State” })
        @Html.ValidationMessage(“State”, “*”)
        @Html.Label(“District”)
        <select id=”District” name=”District”></select>
        @Html.ValidationMessage(“District”, “*”)
        <p>
            <input type=”submit” value=”Create” id=”SubmitId” />
        </p>
    </fieldset>
}
You can see I have added proper labels and validation fields with each input controls (two DropDownList and one TextBox) and also a validation summery at the top. Notice, I have used <select id=”District”….> which is HTML instead of Razor helper this is because when we make JSON call using jQuery will return HTML markup of pre-populated option tag. Now, let’s add jQuery code in the above view page.
Step 4
Here is the jQuery code making JSON call to DDL named controller’s DistrictList method with a parameter (which is selected state name). DistrictList method will returns JSON data. With the returned JSON data we are building <option> tag HTML markup and attaching this HTML markup to ‘District’ which is DOM control.
@Scripts.Render(“~/bundles/jquery”)
<script type=”text/jscript”>
    $(function () {
        $(‘#State’).change(function () {
            $.getJSON(‘/DDL/DistrictList/’ + $(‘#State’).val(), function (data) {
                var items = ‘<option>Select a District</option>’;
                $.each(data, function (i, district) {
                    items += “<option value=’” + district.Value + “‘>” + district.Text + “</option>”;
                });
                $(‘#District’).html(items);
            });
        });
    });
</script>
Please make sure you are using jQuery library references before the <script> tag.
Step 5
In above jQuery code we are making a JSON call to DDL named controller’s DistrictList method with a parameter. Here is the DistrictList method code which will return JSON data.
    public JsonResult DistrictList(string Id)
    {
        var district = from s in District.GetDistrict()
                        where s.StateName == Id
                        select s;
        return Json(new SelectList(district.ToArray(), “StateName”, “DistrictName”), JsonRequestBehavior.AllowGet);
    }
Please note, DistrictList method will accept an ‘Id’ (it should be ‘Id’ always) parameter of string type sent by the jQuery JSON call. Inside the method, I am using ‘Id’ parameter in linq query to get list of matching districts and conceptually, in the list of district data there should be a state field. Also note, in the linq query I am making a method call District.GetDistrict().
Step 6
In above District.GetDistrict() method call, District is a model which has a GetDistrict() method. And I am using GetDistrict() method in linq query, so this method should be of type IQueryable. Here is the model code.
    public class District
    {
        public string StateName { get; set; }
        public string DistrictName { get; set; }
        public static IQueryable<District> GetDistrict()
        {
            return new List<District>
            {
                new District { StateName = “Bihar”, DistrictName = “Motihari” },
                new District { StateName = “Bihar”, DistrictName = “Muzaffarpur” },
                new District { StateName = “Bihar”, DistrictName = “Patna” },
                new District { StateName = “Jharkhand”, DistrictName = “Bokaro” },
                new District { StateName = “Jharkhand”, DistrictName = “Ranchi” },
            }.AsQueryable();
        }
    }
Step 7
You can run the application here because cascading dropdownlist is ready now. I am going to do some validation works when user clicks the submit button. So, I will add another action result of POST version.
    [HttpPost]
    public ActionResult Index(ApplicationForm formdata)
    {
        if (formdata.Name == null)
        {
            ModelState.AddModelError(“Name”, “Name is required field.”);
        }
        if (formdata.State == null)
        {
            ModelState.AddModelError(“State”, “State is required field.”);
        }
        if (formdata.District == null)
        {
            ModelState.AddModelError(“District”, “District is required field.”);
        }
        if (!ModelState.IsValid)
        {
            //Populate the list again
            List<SelectListItem> state = new List<SelectListItem>();
            state.Add(new SelectListItem { Text = “Bihar”, Value = “Bihar” });
            state.Add(new SelectListItem { Text = “Jharkhand”, Value = “Jharkhand” });
            ViewBag.StateName = new SelectList(state, “Value”, “Text”);
            return View(“Index”);
        }
        //TODO: Database Insertion
        return RedirectToAction(“Index”, “Home”);
    }

And, this action result will accept ApplicationForm model data and based on posted data will do validations. If a validation error occurs, the action method calls the AddModelError method to add the error to the associated ModelState object. The AddModelError method accepts the name of the associated property and the error message to display. After the action method executes the validation rules, it uses the IsValid property of the ModelStateDictionary collection to determine whether the resulting data complies with the model.

Creating a cascade dropdown in MVC & C# (version 1)

 

public class MyViewModel
{
    public int? Year { get; set; }
    public int? Month { get; set; }

    public IEnumerable<SelectListItem> Years
    {
        get
        {
            return Enumerable.Range(2000, 12).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = x.ToString()
            });
        }
    }
}

 

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    public ActionResult Months(int year)
    {
        if (year == 2011)
        {
            return Json(
                Enumerable.Range(1, 3).Select(x => new { value = x, text = x }), 
                JsonRequestBehavior.AllowGet
            );
        }
        return Json(
            Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
            JsonRequestBehavior.AllowGet
        );
    }
}

 

@model AppName.Models.MyViewModel

@Html.DropDownListFor(
    x => x.Year, 
    new SelectList(Model.Years, "Value", "Text"),
    "-- select year --"
)

@Html.DropDownListFor(
    x => x.Month, 
    Enumerable.Empty<SelectListItem>(),
    "-- select month --"
)

<script type="text/javascript">
    $('#Year').change(function () {
        var selectedYear = $(this).val();
        if (selectedYear != null && selectedYear != '') {
            $.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
                var monthsSelect = $('#Month');
                monthsSelect.empty();
                $.each(months, function (index, month) {
                    monthsSelect.append($('<option/>', {
                        value: month.value,
                        text: month.text
                    }));
                });
            });
        }
    });
</script>

Displaying a datatable

To display a Data Table:

@model System.Data.DataTable
@using System.Data;

<h2>View Table</h2>

<table>
    <thead>
    <tr>
    @foreach (DataColumn col in Model.Columns)    
    {         
        <th>@col.ColumnName</th>
    }    
    </tr>
    </thead>        
    <tbody>
    @foreach (DataRow row in Model.Rows)    
    {        
        <tr>
        @foreach (DataColumn col in Model.Columns)        
        {             
            <td>@row[col.ColumnName]</td>
        }        
        </tr>
    }    
    </tbody>
</table>

You can get data as follows:

public DataTable GetDataForSql(string sql, string connectionString)
{
    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        using(SqlCommand command = new SqlCommand())
        {
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.CommandText = sql;
            connection.Open();          
            using(SqlDataReader reader = command.ExecuteReader())
            {
                DataTable data = new DataTable();
                data.Load(reader);
                return data;
            }

        }

    }

}

If you just wanted a DataTable then the following method is short and reduces complexity:

<code>public DataTable GetDataForSql(string sql, string connectionString)
{
    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        using(SqlCommand command = new SqlCommand())
        {
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.CommandText = sql;
            connection.Open();          
            using(SqlDataReader reader = command.ExecuteReader())
            {
                DataTable data = new DataTable();
                data.Load(reader);
                return data;
            }

        }

    }

}</code>

usage:

<code>try{
    DataTable results = GetDataForSql("SELECT * FROM Table;", ApplicationSettings["ConnectionString"]);
}
catch(Exception e)
{
    //Logging
    //Alert to user that command failed.
}</code>

create an image on the fly in c# mvc / asp.net

If you would like to create an image on the fly in c# mvc / asp.net, here’s the code:

<%@ Page Language="C#" %>
<%@ import Namespace="System.Drawing" %>
<%@ import Namespace="System.Drawing.Imaging" %>
<%@ import Namespace="System.Drawing.Drawing2D" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    private void Page_Load(object sender, EventArgs e)
    {
        // Set the page's content type to JPEG files
        // and clears all content output from the buffer stream.
        Response.ContentType = "image/jpeg";
        Response.Clear();

        // Buffer response so that page is sent
        // after processing is complete.
        Response.BufferOutput = true;

        // Create a font style.
        Font rectangleFont = new Font(
            "Arial", 10, FontStyle.Bold);

        // Create integer variables.
        int height = 100;
        int width = 200;

        // Create a random number generator and create
        // variable values based on it.
        Random r = new Random();
        int x = r.Next(75);
        int a = r.Next(155);
        int x1 = r.Next(100);

        // Create a bitmap and use it to create a
        // Graphics object.
        Bitmap bmp = new Bitmap(
            width, height, PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmp);

        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.Clear(Color.LightGray);

        // Use the Graphics object to draw three rectangles.
        g.DrawRectangle(Pens.White, 1, 1, width-3, height-3);
        g.DrawRectangle(Pens.Aquamarine, 2, 2, width-3, height-3);
        g.DrawRectangle(Pens.Black, 0, 0, width, height);

        // Use the Graphics object to write a string
        // on the rectangles.
        g.DrawString(
            "Bitlink Rocks!", rectangleFont,
            SystemBrushes.WindowText, new PointF(10, 40));

        // Apply color to two of the rectangles.
        g.FillRectangle(
            new SolidBrush(
                Color.FromArgb(a, 255, 128, 255)),
            x, 20, 100, 50);

        g.FillRectangle(
            new LinearGradientBrush(
                new Point(x, 10),
                new Point(x1 + 75, 50 + 30),
                Color.FromArgb(128, 0, 0, 128),
                Color.FromArgb(255, 255, 255, 240)),
            x1, 50, 75, 30);

        // Save the bitmap to the response stream and convert it to JPEG format.
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);

        // Release memory used by the Graphics object
        // and the bitmap.
        g.Dispose();
        bmp.Dispose();

        // Send the output to the client.
        Response.Flush();
    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>ASP.NET picture</title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

 

 

working with links

this will perform a “Back” operation:

@Html.ActionLink(“Quick Login”, “Login”, “Account”, null, new { data_icon = “arrow-r”, data_rel = “back” })

Taking a website offline

Taking a website offline
Just create a file called:
app_offline.htm
in the root folder

MVC Razor – working with combobox/dropdown controls

Rendering a dropdown in MVC with an id and preselected value etc.

Class

public class Ward 
{
    public int Ward_id{get ;set;}
    public string Ward_name{get ;set;}
    public List<Wards> GetAll() 
    {
        //code here
    }
}

 

Controller:

model.Wards = Ward.GetAll();
model.Wards.Insert(0,new Wards() { Ward_name="all", Ward_id = -1});
model.SelecteWardId = id;

View:

 

@Html.DropDownListFor(n => n.Wards, new SelectList(
    Model.Wards,"Ward_id","Ward_name", Model.SelecteWardId),
        new Dictionary<string, object> { { "id", "TheIdForTheDropdown" }
        { //can add click events etc here too 
  } })

this renders:

<select id="TheIdForTheDropdown" name="Wards"><option value="-1">all</option>
<option value="1">A</option>
<option selected="selected" value="2">B</option>
<option value="3">C</option>
</select>