Kuttan Sujith
Kuttan Sujith

Reputation: 7979

Method overloading in Controller

I have 2 methodS as given below

public string Download(string a,string b) 
public string Download(string a)

But MVC3 With IIS 5.1 gives run time error that this 2 mehods are ambiguious.

how can i resolve this problem?

Upvotes: 2

Views: 503

Answers (2)

RredCat
RredCat

Reputation: 5421

To my mind you should try to use ASP.NET Routing. Just add new MapRoute. You can check example in this post

Upvotes: 0

moribvndvs
moribvndvs

Reputation: 42497

Since string is nullable, those overloads truly are ambiguous from the standpoint of MVC. Just check if b is null (perhaps make it an optional parameter, if you'd like a default value).

You could, on the other hand, try a custom ActionMethodSelectorAttribute implementation. Here is an example:

public class ParametersRequiredAttribute : ActionMethodSelectorAttribute
    {
        #region Overrides of ActionMethodSelectorAttribute

        /// <summary>
        /// Determines whether the action method selection is valid for the specified controller context.
        /// </summary>
        /// <returns>
        /// true if the action method selection is valid for the specified controller context; otherwise, false.
        /// </returns>
        /// <param name="controllerContext">The controller context.</param><param name="methodInfo">Information about the action method.</param>
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            var parameters = methodInfo.GetParameters();

            foreach (var parameter in parameters)
            {
                var value = controllerContext.Controller.ValueProvider.GetValue(parameter.Name);

                if (value == null || string.IsNullOrEmpty(value.AttemptedValue)) return false;
            }

            return true;
        }

        #endregion
    }

Usage:

[ParametersRequired]
public string Download(string a,string b)


// if a & b are missing or don't have values, this overload will be invoked. 
public string Download(string a)

Upvotes: 3

Related Questions