a developer's notes – a semi-technical web development BLOG

August 5, 2014

How to Redirect user or execute Controller Action in a Custom MVC Filter

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 12:41 pm
Tags: , , , , ,

MVC Filter

    public class MyFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // The controller will be the controller you add the filter to. Or some base controller
            var controller = filterContext.Controller as YourController;

            // Execute controller action from filter. 
            controller.SomeControllerMethod();

            // Redirect to controller action
            filterContext.Result = new RedirectToRouteResult( new System.Web.Routing.RouteValueDictionary
            {
                {"controller", "mycontroller"},    
                {"action", "myaction"},
                {"querystring", "?hello=true"}
            });

            // Redirect to external url
            filterContext.Result = new RedirectResult(url);
        }
    }

January 29, 2014

Dynamically added checkbox not posting value to Action Method in controller

I noticed that @Html.CheckboxFor(model => model.MyCheckBox) creates a hidden input with the same name as the actual checkbox. So when you dynamically add a checkbox, make sure you also add in a hidden input with the same name attribute.


var chkboxDiv = $(document.createElement('div')).attr({
	id: 'dynamicChkBoxdiv_'
});

chkboxDiv.html(
	'<input ' +
		'class="myChkBx"' +
		'type="checkbox"' +
		'value=""' +
		'data-val-required="The Active field is required."' +
		'data-val="true"' +
		'name="myChkBxName"/>' +
	'<input ' +
		'type="hidden"' +
		'value=""' +
		'name="myChkBxName"/>' +
);

You also need to add a click event handler to update the hidden value so when the form is submitted, the controller will get the correct ‘checked’ value.

Notice the second parameter that specifies a css class. When you add your dynamic controls, add a css class so you can specify which elements should get the click event delegate. All of your dynamically added controls that have the css class, will now have the same click event.

$("#dynamicChkBoxdiv_").parent().on("click", '.myChkBx', function (e) {
	var name = e.target.name;
	var checkVal = e.target.checked;
	$("input[name^='" + name + "']").val(checkVal); //this will update both the checkbox and hidden input's value
});

March 31, 2013

Action and Func delegates in .NET extension methods

Filed under: C# — Duy Nguyen @ 7:11 pm
Tags: , , , , ,

The Action delegate never returns a value.

// no params
Action printEmptyLine = () => Console.WriteLine();

// one param
Action printNumber = x => Console.WriteLine(x);

// two params
Action<int, int> printTwoNumbers = (x, y) =>
                 {
                     Console.WriteLine(x),
                     Console.WriteLine(y)
                 };

A Func delegate returns some sort of value.

// at minimum, you have to specify the return type
Func getTime = () => DateTime.Now; // returns a type DateTime

// two params. The last param is the return type.
Func<int, int> square = x => x * x; // takes an int, returns an int

// three params
Func<int, int, int> multiple = (x, y) => x * y; // takes an int, returns an int

Using the delegates, you can just invoke them like this:

// using Action delegates
printEmptyLine();
printNumber(3);
printTwoNumbers(5, 10);

//using Func delegates
DateTime now = getTime();

Now when you use extension methods, will understand what it needs.

For example:
whereFunc
So the above, you know the where method takes a Employee type and returns a bool.

A Linq Expression

//This is the same Func delegate but there is an Expression Type around it.
Expression<Func<int, int, int>> multipleExpression = (x, y) => x * y; // takes an int, returns an int

You can’t just invoke expressions. You’d have to turn them back into delegates to use. Like this:

Func<int, int, int>> multipleExpression = multipleExpression.Compile();

Expressions are mainly used for Linq to SQL. Func and Action delegates are used in Linq to Objects.

When using any extension method, if you see a parameter for a Func, Action, or Expression, they all accept lambda expressions.

Blog at WordPress.com.