Tag Archives: MVC

HTTP Status Codes

HTTP Status Codes

Each Status-Code is described below, including a description of which method(s) it can follow and any metainformation required in the response.

1xx – Informational

This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions.

A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Unexpected 1xx status responses MAY be ignored by a user agent.

Proxies MUST forward 1xx responses, unless the connection between the proxy and its client has been closed, or unless the proxy itself requested the generation of the 1xx response. (For example, if a proxy adds a “Expect: 100-continue” field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s).)

2xx – Successful

This class of status code indicates that the client’s request was successfully received, understood, and accepted.

3xx – Redirection

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.  The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.

Note: previous versions of this specification recommended a maximum of five redirections. Content developers should be aware that there might be clients that implement such a fixed limitation.

4xx – Client Error

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

If the client is sending data, a server implementation using TCP SHOULD be careful to ensure that the client acknowledges receipt of the packet(s) containing the response, before the server closes the input connection. If the client continues sending data to the server after the close, the server’s TCP stack will send a reset packet to the client, which may erase the client’s unacknowledged input buffers before they can be read and interpreted by the HTTP application.

5xx – Server Error

Response status codes beginning with the digit “5” indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. User agents SHOULD display any included entity to the user. These response codes are applicable to any request method.

Binding & posting to a Dictionary in MVC 3 using jQuery

Binding, posting to a Dictionary in MVC 3 using jQuery ajax

In this post we are going to discuss how to post data to a Dictionary using jQuery ajax. Lets have a simple model from the previous post and pass value to the action method as dictionary of the model we get the following controller method.

public ActionResult Binding_posting_to_a_dictionary_using_ajax(Dictionary<string, UserModel> userList)
    return PartialView("Success");

To work with dictionary the default model binder will accept the data in a particular format. If we consider key of the first element of the dictionary as firstkey then we have to give the name of the input parameter as [0].value.ModelPropertyName. So, for the first item we can give the names like-

<input name="[0].key" value="firstkey" type="hidden">
<input name="[0].value.FirstName" value="" type="text">
<input name="[0].value.LastName" value="" type="text">
<input name="[0].value.Age" value="" type="text">

If we see the above code block, we can see there is a hidden field for maintaining the key of the dictionary element and the value of the hidden filed is nothing but the key of the dictionary element

<div class="data">
        First User</h4>
    <input type="hidden" name="[0].key" value="first" />
    First Name: @Html.TextBox("[0].value.FirstName")
    Last Name: @Html.TextBox("[0].value.LastName")
    Age: @Html.TextBox("[0].value.Age")
<div class="data">
        Second User</h4>
    <input type="hidden" name="[1].key" value="second" />
    First Name: @Html.TextBox("[1].value.FirstName")
    Last Name: @Html.TextBox("[1].value.LastName")
    Age: @Html.TextBox("[1].value.Age")
<div class="data">
        Third User</h4>
    <input type="hidden" name="[2].key" value="third" />
    First Name: @Html.TextBox("[2].value.FirstName")
    Last Name: @Html.TextBox("[2].value.LastName")
    Age: @Html.TextBox("[2].value.Age")
<input type="button" id="submitData" value="Submit data" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#submitData").click(function () {
            var datatopost = new Object();
            $(".data").each(function (i, item) {
                datatopost[$(item).find("input[name*=FirstName]").attr("name")] = $(item).find("input[name*=FirstName]").val();
                datatopost[$(item).find("input[name*=LastName]").attr("name")] = $(item).find("input[name*=LastName]").val();
                datatopost[$(item).find("input[name*=Age]").attr("name")] = $(item).find("input[name*=Age]").val();
                datatopost[$(item).find("input[name*=key]").attr("name")] = $(item).find("input[name*=key]").val();
                url: '@Url.Action("Binding_posting_to_a_dictionary_using_ajax")',
                type: 'POST',
                traditional: true,
                data: datatopost,
                dataType: "json",
                success: function (response) {
                error: function (xhr) {

Injecting Repository into Custom Action Filter using Unity

create UnityFilterAttributeFilterProvider .cs class
public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider

private readonly IUnityContainer _container;

public UnityFilterAttributeFilterProvider(IUnityContainer container)
_container = container;

protected override IEnumerable<FilterAttribute> GetControllerAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
var attributes = base.GetControllerAttributes(controllerContext, actionDescriptor).ToList();
foreach (var attribute in attributes)
_container.BuildUp(attribute.GetType(), attribute);

return attributes;

protected override IEnumerable<FilterAttribute> GetActionAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
var attributes = base.GetActionAttributes(controllerContext, actionDescriptor).ToList();
foreach (var attribute in attributes)
_container.BuildUp(attribute.GetType(), attribute);

return attributes;

In global.asax
protected void Application_Start() {
// ...

var oldProvider = FilterProviders.Providers.Single(
f => f is FilterAttributeFilterProvider

var container = new UnityContainer();
var provider = new UnityFilterAttributeFilterProvider(container);

// ...

Since Unity is not instantiating the Filters, it cannot inject them. You would have to resort to service locator pattern such as in the following:
Authenticate is the custom action filter where I am injecting IAuthenticate and ILibrary repository
public class Authenticate : AuthorizeAttribute
public IAuthenticate AuthenticateLibrary { get; private set; }

public ILibrary BaseLibrary { get; private set; }

public Authenticate()
AuthenticateLibrary = DependencyResolver.Current.GetService<IAuthenticate>();
BaseLibrary = DependencyResolver.Current.GetService<ILibrary >();

ViewComponents in ASP.NET 5 and ASP.NET MVC 6

Let’s have a quick look at another new feature in ASP.NET MVC 6, and that is the ViewComponent feature. View components are intended to be replacements to ChildActions and, to some extent, of partial views.

Traditionally in ASP.NET MVC (and in general in the textbook MVC pattern), you had to compose the entire model in the controller and pass it along to the view, which simply rendered the entire page based on the data from the model. The consequence of this is that the view does not need to explicitly ask for any data – as its sole purpose is to just act upon the model it received.

While this sounds very nice in theory, it has traditionally posed a number of practical difficulties. There are a number of reusable components on pretty much every website – think a menu, a shopping cart, lists of all kinds, breadcrumbs, metadata and so on – so things that appear on multiple pages.

Let’s have a look at how this is solved in MVC 6.

The reusable component problem

Having to compose and gather the data required to create these components in multiple controllers over and over can be really painful, and has often led developers to create a all kinds of model builders and inherited models (have you ever created aBaseModel containing things like menu or page metadata?).

One way to easy that pain was to try to use child actions – which were actions that could only be called from the view (not publicly by the client). I have seen plenty of MVC projects that used child actions to render such reusable components. Another alternative has always been to create elaborate HtmlHelpers. Unfortunately since the helpers were static, you couldn’t do dependency injection into them, so trying to load any extra data for the purpose of such helper, would require you to use service locator – the MVC global DependencyResolver.

View components are really a mesh of both HtmlHelper and child actions.

ViewComponents example

Consider the following sample service:

It’s not unreasonable to think that you might have code resembling something that in your projects. Imagine that we need to display a list of these promoted products in multiple places on the website.

Typically in MVC 5 and earlier, you would have a child action, an HtmlHelper or a base model builder to handle this. With view component you can simply add a view component class:

That class can use ASP.NET 5 dependency injection – which is very convenient. It can return something primitive like a JSON or a string, but it can also have its own partial view; in the above example the partial exists under/Views/Shared/Components/{componentname}/Default.cshtml. The Default.cshtml is the default convenion for all views of view component. You can also pass the name of the view returning i.e. return View(“_Products”, products)

In our case the Razor view would look like you would expect any partial view to look:

In order to embed this view component into a proper, main view, you use the Component property of the Razor pages – in the form of the following syntax:

There is also a sync version, if your component is synchronous. And that’s about it – a bit against the textbook MVC pattern, but very convenient and much cleaner than the old approaches or workarounds we had to use.

Some background info

In order for a class to be recognized as a view component, it needs to be:

  • public
  • non-abstract
  • non generic
  • end with ViewComponent suffix or be decorated with ViewComponentAttribute

As you can see, just like the rest of MVC 6, it heavily relies on conventions. To build a view component you do not need to inherit from any specific class or implement any interface.

As far as the actual functionality inside your view component, it is also defined by convention – it should be wrapped in one of the following methods (the method name and return type are important):

The default view component invoker (which could be changed if you wish) will first try to look for the async method, and if it’s not found, then it will try to fallback to the sync version. Afterwards, if it’s still not found, you’ll get a runtime error. This is important to note, because given the above mentioned requirements for a class to be considered a valid view component, it is still possible to get a runtime error if you misspell or misname the actual Invoke method.

Depending on what you need to do, there is a base class ViewComponent, which you can choose to inherit from for your own convenience. It will give you – through it’s expose properties – access to all contextual information about the view such as user principal information, current HttpContext, ViewData and all other information you typically would have inside a view. It will also allow you to easily attach a Razor view to the view component – which you can do by calling the base View() method when returning from your view component.

As far as discovery of view components goes, all assemblies that reference ASP.NET MVC packages will be considered valid to search. This is particularly important for developers of reusable, CMS-like components that are intended to be used cross-project. The discovery is controlled by a type called DefaultViewComponentDescriptorProvider, which allows you to extend itself with additional source to look at or provide different rules for the class to be recognized as view component.

Finally, it is also possible to pass data to the components. Then you add the relevant parameters to the signature, for example:

In order to invoke such a component from a view, you use an overload of the Component.InvokeAsync which takes param ofobject[]:

Protection against SQL injection

Protection against SQL injection needs to take place on server side, regardless where the incoming call comes from.

Javascript-based sanitation methods are always useless because Javascript runs on client side, and therefore can be forged.

This also applies for AJAX calls: The client doesn’t need to turn JavaScript off; they just need to manipulate the Javascript code they download from your site to fake validation.

CDN in ASP.NET MVC bundling

Once you create ASP.NET MVC project and you looked into the App_start folder BundleConfig.cs file you will fine following code for jQuery bundle.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

Here you can see that there is a ScriptBundle object created with new. This ScriptBundle object also contains another constructor which also take path of cdn as parameter.

Now let’s first run application without adding CDN and see how its works.


You can see its loaded from bundle not using any CDN there. So Let’s see how we are going to use CDN there. There are lots of CDNs are available there but I’m going to use Microsoft Hosted CDN file in our sample application.

You can find all CDN hosted file on following location.


and here all the jQuery CDN listing for all the versions.


I’m going to use jQuery 1.10.2 version as ASP.NET MVC application by default comes with that version only. Following is a code for that.

bundles.UseCdn = true;
   bundles.Add(new ScriptBundle("~/bundles/jquery",

Here you can see that I have used path without http so that whether you use https or http it will work on both side. Also you can see that I have enabled UseCdn proper to true that will tell bundle to use CDN whenever its available.

As CDN is used in release version, to test application we need to set Debug=”False” in our web.config check that in local machine. So once you are done with that and run in browser you can see in below image its using CDN instead of local file.


bundle files in specific order


internal class AsIsBundleOrderer : IBundleOrderer
    public virtual IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
        return files;

internal static class BundleExtensions
    public static Bundle ForceOrdered(this Bundle sb)
        sb.Orderer = new AsIsBundleOrderer();
        return sb;


    bundles.Add(new ScriptBundle("~/content/js/site")

I like using fluent syntax but it also works with a single method call and all the scripts passed as parameters.

MVC RenderPartial pass parameters

In my ASP.NET MVC 4 partial view, I was having an issue where VaidationSummary and VaidationMessageFor were coming up blank. I scratched my head on this for quite some time. I finally came across this entry at the MVC forums at MSDN. It turns out I wasn’t passing the ViewData from parent view, but in fact my own fresh ViewData. This is how I had things before:

The Wrong Way

Html.RenderPartial(“_CreateEditDisplay”, Model, new ViewDataDictionary { { “Submit”, true }, { “Action”, “Edit” }, { “ReadOnly”, false } });

The Right Way
I figured it out by doing this instead:

Html.ViewData.Add(new KeyValuePair<string, object>(“Submit”, true));
Html.ViewData.Add(new KeyValuePair<string, object>(“Action”, “Edit”));
Html.ViewData.Add(new KeyValuePair<string, object>(“ReadOnly”, false));

Html.RenderPartial(“_CreateEditDisplay”, Model, Html.ViewData);

Basically what we have here is the original ViewData from the parent view with my additional add-ons that are passed to the partial view. Once I made this change, the ModelState is propagated to the partial view and VaidationSummary and VaidationMessageFor are outputting the desired results.

Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”

Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”

I ran into this and it was caused by the entity’s ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity’s ID has been set.