Tag Archives: HyperLink


[RESOLVED]Browser Info in MVC


I need to capture the browsers info and count no. of requests coming from the browser.

and also i need to block the request , if the request comes from a specified browser say FireFox

Depending on these requests and their count, i need to generate a report or a chart in dashboard.



The browser info in in the agent string header. Here is site that keeps track of the current agent strings. New ones appear with every new phone.


You get the agent string with Request.UserAgent.

For hit tracking you process your web logs, or use google analytics.

You can use a MVC filter or constraint to handle your scenario. Please check these links

Filter actions based on UserAgent

ASP.NET MVC: Custom Constraints – Matching the User Agent String


Depending on these requests and their count, i need to generate a report or a chart in dashboard

It would be better if you can use some analytic services such as google analytics for this.

[RESOLVED]Authorize Attribute

Hi All, 

I am writing my custom Authorize attribute..

but I need to initialize my service with two paramteres  which in turn calls the repository

How can I initialize service or repository ?

Please help 




How can I initialize service or repository ?

Can you show some relevant parts of your code? Are you using dependency injection? …

Grz, Kris.


I need to initialize my service with two paramteres

Do you mean to pass parameters to you custom Authorize attribute. In that case you can pass it as a parameter. Please take a look at this stack overflow post

create the authorize filter with parameter asp.net mvc

[RESOLVED]Html.Helpers or Html tags ?

When we are developing our views, we can set codes as HTML.Helpers or write them as HTML tags.
However what’s best ?


1. @Html.ActionLink("About this Website", "About")

2. <a href="/Home/About">About this Website</a>

a) So what should I use ? Should I write the HTML tags directly without razor or use helpers ?
b) If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

You can choose either. I personally use both, depending to where I’m linking.

For members and registered users, on an ASP.net project, I usually use the helpers, and on any pages accessible to unauthenticated users I use the <a href=""></a> tags.

If you use the Html.ActionLink helper, the url will always be constructed properly regardless of changes in the hosting environment, or changes between development, testing and production environments. This might not be an issue to you in which case feel
free to hard code your links. 

I have full control over my hosting environment and make sure that the development environment mirrors it as much as possible. Despite that, I use the helpers just in case. 


If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

Yes, but it is so insignificant that if you have to worry about it, you have much bigger problems.


Hi, i did this simple query, where i show in my list of magazine only the one belonging to the menuid choosen in the link but it doe not work

Query :

 //I  think you can actually drop the Likes include as it will be included with the Likes.Select include, so maybe try this (although if it doesn't work, use the first example which should):
            var magazines = db.Magazines.Include(m => m.ParentMenuMag).Include(m => m.ParentSubMenuMag).Include(m => m.Likes.Select(l => l.User)) as IQueryable<Magazine>;

            if (menuid.HasValue)
                magazines = magazines.Where(r => r.ParentMenuMag.MenuId.Equals(menuid.Value));


<a href="@Url.RouteUrl("MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })" title="@MenuName">@MenuName<i class="fa fa-angle-down"></i></a>    

Result link

<a href="/Magazine/Index/1/styles-inspirations" title="Styles &amp; Inspirations">Styles &amp; Inspirations<i class="fa fa-angle-down"></i></a> 


            name: "MagazineRoute",
            url: "{controller}/{action}/{menuid}/{menuname}/{submenuid}/{submenuname}/{id}",
            defaults: new { controller = "Magazine", action = "Index", menuid = UrlParameter.Optional, menuname = UrlParameter.Optional, submenuid = UrlParameter.Optional, submenuname = UrlParameter.Optional, id = UrlParameter.Optional }

What is wrong?

You question was not clear for me. I didn’t understand the relation between the hyperlink and the query.



does not work

It’s best to always tell what is the error or behavior you see. For example it can happen that the problem is unrelated to what you shown in which case someone will waste time in trying to find what is the error you have (that is an information that you
know already) rather than on how to solve your issue.

HI, no error.. just i see all the item of the list and not only the onewith the idmenu choose…

in fact the query  has not be called.. why? th idmenu exist

Even the behavior is helpfull. So for now it would seem that menuid.HasValue is false. Please use the VS debugger to see if this is the case. From what you
shown I don’t see why.

menuid is part of your action signature I suppose? (and so I could’t imagine that without knowing what actually happens).

Try /Magazine/Index/1/a/2/b/3 in your browser and see in the VS debugger if the various values are correctly populated etc…

The problem is that if i change my link :

<a href="@Url.RouteUrl("MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })" title="@MenuName">@MenuName<i class="fa fa-angle-down"></i></a>    

like this :

@Html.RouteLink(MenuName, "MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })</li>

it works perfectly… so the problem, i guess is in the  @Url.RouteUrl(", becaus if i use the
@Html.RouteLink( the query can find the menuid.HasValue

How comes?

What if using "view source" in both cases to see which HTML markup is generated and see how they differ?

[RESOLVED]Download form to Pdf on button click

Can anyone help me download the selected form on button click to pdf  in MVC ….

or anyother way to do it.

So you need to convert a form to PDF?  I use the NuGet package "Rotativa" to convert anything to PDF.  There’s good documentation on it as well


How to add it in my project???

can u suggest me pls


You can use Nuget to install it. Go to the Nuget console manager and run the command (as mentioned in the post)

Install-Package Rotativa

For information on how to run Nuget from console see the below post


i have installed Rotativa in my project..

but i m not able to proceed furthur;

can u provide me with sample video for downloading form on button click

Try downloading the demo from the site and run it


I m getting this error how do i resolve it?

Error 19 The type or namespace name ‘ControllerContext’ could not be found (are you missing a using directive or an assembly reference?) E:PersonalInformationLearningAjaxRotativa-PartialViewAsPdfRotativa-PartialViewAsPdfRotativaAsPdfResultBase.cs 229
44 Rotativa

Can you explain little bit more on what you want to do on the button click. What data you want to convert into pdf and where does this data reside?

Also are you ok with use commercial products which will simplify your work?

I have two buttons on everypage when i view data of a particular client …..print button and download button//…..

print is ok…

now i need code for downloading the particular html page to pdf ……

can u help me with this?

Is it ok to pass your data to a third party website which converts your page to pdf. If yes try this

<a href="javascript:void(window.open('http://www.htmltopdfconverter.net/?convert='+window.location))">Convert To PDF</a>

Also check this stack overflow
convert HTML ( having Javascript ) to PDF using java / javascript

[RESOLVED]Strange behavior from Create View

I have an ASP.Net MVC 4 web app.  I  have this one particular controller.  The index view for this controller has three partial views on it.  The first partial view always loads when the view is called.  It uses a renderAction html helper.  The other two
are called as a result of ajax function calls within the create view.

The index view has a JQuery datatables library included which is built using JqueryUI.  There are no JQueryUI components on the Create View.

As the result of a button click, the Create view calls a function which first calls one ajax function to save the data to the database, then another ajax call to the action used by the renderAction to build the first partial view.  This function was devised
months ago and has been running without an issue.   Then suddenly today, the button click would save the data, then open the index view.  This was not the expected behavior.  When I stepped through the code line by line I found that the pratial view was in
fact bveing loaded into the proper location on the create view.  And in fact when doing so the proper window opened in IE.  But then a bunch of additional code in modernizer, Jquery-1.8.2 and jQuery-UI-1.8.24 started running and when it completed it opened
on the Index view.  I have no idea how this happened.  See the code below

First I called an ajax like so

    $(function () {
        var PopulatePRs = function () {
            var sURL = '@Url.Action("CreatePurchaseRequest", "AJAXFunctions")';
            var goURLid = 0;
            var form = $("#PRCreate");
            var bError = false;
            var sResultMessage = '';

                url: sURL,
                type: 'POST',
                data: form.serialize(),
                cache: false,
                async: false,
                dataType: 'json',
                //contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    if (data != null) {
                        $(data).each(function () {
                            goURLid = data;
                    else {
                        returnedInfo = 'An Error has occurred. Your new PR was not saved to the database.';
                        bError = true;
                        goURLid = 0;
                error: function () {
                    returnedInfo = 'An Error has occurred. Your new PR was not saved to the database.';
                    bError = true;
                    goURLid = 0;

This works fine.   I have verified in the database that the ajax call was successful.  Then the following ajax function is called to call the action that rebuilds the partial view.

            //if (!bError) {
            var sURLRepost = '@Url.Action("PurchaseRequestTable", "PR")' + '/' + goURLid;
            var options = {
                url: sURLRepost,
                type: "get",
                async: false
            $.ajax(options).done(function (data) {

            if (!bError) {
                sResultMessage = "The new Purchase Request has been saved to the database.nClick below to add CLINs and CDRLs.";
            else {
                sResultMessage = returnedInfo;

The action is properly called the ajax call which I was able to verify by putting a breakpoint in the action and stepping through it and I was able to hover over the "data" variable and verify that the proper html was being returned to replace $("#PRtableView"). 
Finally I was able to verify the sResultMessage was replacing the text of $("#PRCreated").  Then I actually saw the window open looking as it is supposed to.

Then the part of modernizer that starts with the below code ran:

window.Modernizr = (function( window, document, undefined ) {

    var version = '2.6.2',

    Modernizr = {},


    // option for enabling the HTML classes to be added

    enableClasses = true,


Then in JQuery-1.8.2 the function that starts with this:

(function( window, undefined ) {
	// A central reference to the root jQuery(document)

	// The deferred used on DOM ready

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,
	location = window.location,
	navigator = window.navigator,

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

Then this function

(function( $, undefined ) {

// prevent duplicate loading

// this is only a problem because we proxy existing functions

// and we don't want to double proxy them

$.ui = $.ui || {};

if ( $.ui.version ) {



Then this function

function( $, undefined ) {

// jQuery 1.4+

if ( $.cleanData ) {

	var _cleanData = $.cleanData;

	$.cleanData = function( elems ) {

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {

			try {

				$( elem ).triggerHandler( "remove" );

			// http://bugs.jquery.com/ticket/8235

			} catch( e ) {}


		_cleanData( elems );


} else {

	var _remove = $.fn.remove;

	$.fn.remove = function( selector, keepData ) {

		return this.each(function() {

			if ( !keepData ) {

				if ( !selector || $.filter( selector, [ this ] ).length ) {

					$( "*", this ).add( [ this ] ).each(function() {

						try {

							$( this ).triggerHandler( "remove" );

						// http://bugs.jquery.com/ticket/8235

						} catch( e ) {}




			return _remove.call( $(this), selector, keepData );




Then in JQuery-ui-1.8.24

(function( $, undefined ) {

var mouseHandled = false;

$( document ).mouseup( function( e ) {

	mouseHandled = false;



function( $, undefined ) {

$.widget("ui.draggable", $.ui.mouse, {

	widgetEventPrefix: "drag",


(function( $, undefined ) {

$.widget("ui.droppable", {

	widgetEventPrefix: "drop",

	options: {

		accept: '*',

and a few more $.widget methods.

And when all of these finished, then the index view was opened.

Like I said it did not do that from a couple of months ago up to a couple of days ago.  It did not do this when I first ran it this morning.  It just started to do this, this morning at a demonstration for the customer, and has been doing this ever since.

I am baffeled.  If anyone can point me in the right direction I would be most grateful.

Found it.  This page
 I was advised to put href = "" in my links to make the syle of a link appear on the page.  I had forgotten that I read somewhere that when no index is passed to the url,
then the user is routed to the index method of the controller.  That is what happened here after I made the change referenced above. 

So I will have to hard code a style just for these elements in the style sheet.

Hi joeller,

If the href attribute is not present, the <a> tag is not a hyperlink. In HTML5, if the <a> tag has no href attribute, it is a placeholder for a hyperlink.

# HTML <a> href Attribute


Best Regards

Starain Chen

[RESOLVED]Model Validation Exceptions

Is there anyway I can use model data annotations as just a warning, without too much coding to override?  In other words the message won’t stop progress but clearly warns user of consequences?

you can use jquery alert for warnings instead

Model validation uses JQuery validation plugin. You can use the plugin directly to post the page along with errors. Please see the attached stack overflow post for two ways of doing this

jQuery validation plugin: how can I treat errors as warnings and allow form submit?


  • A custom data annotation attribute for all view models supporting the warning type of validation;
  • A known base class which the view models will inherit from;
  • We’ll have to duplicate the logic in JavaScript for each custom attribute.

Please note that the code below just illustrates the approach and I have to assume quite a lot of things without knowing the full context.

View Model

In this scenario it’s best to separate a view model from an actual model which is a good idea anyway. One possible approach is to have a base class for all view models which support warnings:

public abstract class BaseViewModel
    public bool IgnoreWarnings { get; set; }

The key reason a model needs to be separate is that there’s little sense in storing the 


property in your database.

Your derived view model will then look as follows:

public class YourViewModel : BaseViewModel
    [StringLengthWarning(MaximumLength = 5, ErrorMessage = "Your Warning Message")]
    public string YourProperty { get; set; }


 is a custom data annotation attribute for server and client-side validation. It just supports the maximum length and can easily be extended with any other necessary properties.

Data Annotation Attribute

The core of the attribute is 

IsValid(value, validationContext


[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class StringLengthWarningAttribute : ValidationAttribute, IClientValidatable 
    public int MaximumLength { get; set; }

    public override bool IsValid(object value)
        return true;

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        var model = validationContext.ObjectInstance as BaseViewModel;
        var str = value as string;
        if (!model.IgnoreWarnings && (string.IsNullOrWhiteSpace(str) || str.Length > MaximumLength))
            return new ValidationResult(ErrorMessage);
        return base.IsValid(value, validationContext);

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        yield return new StringLengthWarningValidationRule(MaximumLength, ErrorMessage);

The attribute implements 


 and utilizes a custom client validation rule:

public class StringLengthWarningValidationRule : ModelClientValidationRule
    public StringLengthWarningValidationRule(int maximumLength, string errorMessage)
        ErrorMessage = errorMessage;
        ValidationType = "stringlengthwarning";
        ValidationParameters.Add("maximumlength", maximumLength);
        ValidationParameters.Add("ignorewarningsfield", "IgnoreWarnings");

lient-side JavaScript

Finally, to make it work, you’ll need the following JavaScript referenced from your view:

$(function () {
    $.validator.addMethod('stringlengthwarning', function (value, element, params) {
        var maximumlength = params['maximumlength'];
        var ignorewarningsfield = params['ignorewarningsfield'];

        var ctl = $("#" + ignorewarningsfield);
        if (ctl == null || ctl.is(':checked'))
            return true;
        return value.length <= maximumlength;

    $.validator.unobtrusive.adapters.add("stringlengthwarning", ["maximumlength", "ignorewarningsfield"], function (options) {
        var value = {
            maximumlength: options.params.maximumlength,
            ignorewarningsfield: options.params.ignorewarningsfield
        options.rules["stringlengthwarning"] = value;
        if (options.message) {
            options.messages["stringlengthwarning"] = options.message;


The JavaScript makes some assumptions you might want to revisit (the check-box name, etc).


To display the validation messages separately for errors and warnings, a couple of helpers will be necessary. The following class provides a sample:

public static class  MessageHelpers
    public static MvcHtmlString WarningMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        if (htmlHelper.ViewData.ModelState["IgnoreWarnings"] != null)
            return htmlHelper.ValidationMessageFor(expression);
        return MvcHtmlString.Empty;

    public static MvcHtmlString ErrorMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        if (htmlHelper.ViewData.ModelState["IgnoreWarnings"] == null)
            return htmlHelper.ValidationMessageFor(expression);
        return MvcHtmlString.Empty;

In the view they can be used as usual:

        @Html.EditorFor(model => model.YourProperty)
        @Html.ErrorMessageFor(model => model.YourProperty)
        @Html.WarningMessageFor(model => model.YourProperty)

I’m definitely into View Models and VM inheritance, however, that is a ton of code for a warning….   I see this solution as a long term framework enhancement.

I like the JQUERY validation idea as well. 

And finally, I’ll hop over to Stackoverflow too..

Thanks folks! :)

[RESOLVED]Entity Framework Edit Model

Hello everybody

I just start work with Entity Framework and when I try to edit model I got a error "A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects
in the relationship."

The model what I try to edit is:

    public class CashboxCharge
        [HiddenInput(DisplayValue = false)]
        public virtual Int32 ID { get; set; }

        //[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
        public virtual DateTime Date { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual Int32 OrganizationID { get; set; }

        public virtual Organization Organization { get; set; }

        public virtual IList<CashboxChargeItem> CashboxChargeItems { get; set; }


public class CashboxChargeItem
        [HiddenInput(DisplayValue = false)]
        public virtual Int32 ID { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual Int32 ChargeID { get; set; }

        public virtual Charge Charge { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual Int32 ProgramID { get; set; }

        public virtual Program Program { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual Int32 SpecificityID { get; set; }

        public virtual Specificity Specificity { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual Int32 ArticleExpendureID { get; set; }

        public virtual ArticleExpendure ArticleExpendure { get; set; }

        public virtual float ExSumma { get; set; }
        public virtual float Summa { get; set; }

        [HiddenInput(DisplayValue = false)]
        public virtual Int32 CashboxChargeID { get; set; }

        public virtual CashboxCharge CashboxCharge { get; set; }

For Edit I use code which was created by Add Controller

        public ActionResult Edit(CashboxCharge cashboxcharge, String param)
            if (ModelState.IsValid)
                cashboxcharge.CashboxChargeItems = JSON.Deserialize<IList<CashboxChargeItem>>(param);

                db.Entry(cashboxcharge).State = EntityState.Modified;
            return this.Direct();

Hi VSirchenko,

Thanks for your post.


A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship."

Its seems that in some of its  collections that set the relationship with other entities exist some type of conflict. You could try to clear all the collections to see if the problem persists,  in this case you lost the foreign key assignment. But perhaps
could help you to locate the problem.

More information:

Entity Framework: A referential integrity constraint violation on many to many relationship

A referential integrity constraint violation occurred

Error:A referential integrity constraint violation occurred on db.SaveChanges() in .net?

If there’s anything else I can do for you regarding this matter,please feel free to let me know.

Best Regards,


[RESOLVED]How to work with Web API and MVC together in same project

i search google but not found a details article on How to work with Web API and MVC together in same project.  basically people host web api in separate project but i like to know how could i have web api controller in same mvc project. i want to know how
mvc controller can communicate with web api controller. looking for details discussion with sample code & details instruction. thanks

below article gives you step by step implementation of ASP.NET Web API in MVC application



How to work with Web API and MVC together in same project.

A WebAPI class by default can be placed at any folder in the MVC project. Sometimes I create an API sub folder under Controller folder and keep all my WebAPI controllers.


i want to know how mvc controller can communicate with web api controller

WebAPI is typically called from an Ajax request, i.e, from the browser (though not necessarily). If MVC and WebAPI reside in the project, then there is no point calling a WebAPI from a MVC controller

suppose i need to call web api action from mvc action method then what will be the code……guide me. thanks

Hi mon,

Thanks for your post.

WebApi is an alternative Service oriented application from Microsoft just like WCF. But WCF uses SOAP protocol and WebAPI uses HTTP protocol for communication.

So if you are using WCF to provide service for your MVC application you would host that wcf service seperately and consume its service by MVC application, EXACTLY same way you have to host your WebAPI project seperately and provide service to your Web application

for some reasons if you want them (MVC and WebAPI) to use in the same project, follow this rules from this article.


More information:Add Web API to an existing MVC 5 Web Application

Hope this can be helpful.

Best Regards,



Go through the links I posted. It shows you exactly how to do that.




suppose i need to call web api action from mvc action method then what will be the code

Typically you need to call a Web API that is remotely hosted from MVC. In that scenario please take a look at this post

Calling a Web API From a .NET Client