0

Its very common to have three Edit Actions in one controller all with the same name

  1. Get - Gets the original
  2. Post - Saves the users changes to the database
  3. Delete - Deletes the record from the database

This is done by using attributes HttpGet, HttpPost and HttpDelete. The post is triggered by the normal submit button and the delete is trigger by a submit button with a name="X-HTTP-Method-Override" and a value="Delete".

The problem is this only works for English, as "Delete" is the text of the button. If you change delete to French, "Supprimer", the action with the HttpDelete attribute will not be called. So how do you localize HttpDelete.

Controller:

    [HttpGet]
    public ActionResult Edit(TId id, TSeq seq)
    {
     ...
    }

    [HttpPost]
    [ValidateOnlyIncomingValuesAttribute]
    public ActionResult Edit(TEntity editEntity)
    {
      ...
    }

    // X-HTTP-Method-Override Delete Action
    [HttpDelete]
    public ActionResult Edit(TId id, TSeq seq, TEntity editEntity)
    {
      ...
    }

cshtm Button:

<input type="submit" name="X-HTTP-Method-Override" value="@GlobalResources.Delete" formnovalidate="" class="btn btn-default" onclick="return confirmDelete('@GlobalResources.PromptBeforeDelete')" />
RitchieD
  • 1,831
  • 22
  • 21

1 Answers1

0

Create a custom HttpDelete attribute that handles localization. Simply compare the value from X-HTTP-Method-Override to see if it is "Delete" or whatever language. Ideally, using the same resource as html page, as shown here. Replace the HttpDelete Attribute with the new HttpDeleteLocalized and no changes to the cshtml. :)

using System;
using System.Reflection;
using System.Web.Mvc;

namespace Your.Namespace
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class HttpDeleteLocalizedAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            bool result = false;
            string actionValue = controllerContext.HttpContext.Request.Form.Get("X-HTTP-Method-Override");
            if (actionValue != null)
            {
                if (actionValue == Resources.Delete)
                    result = true;
            }
            return result;
        }
    }
}

Usage:

// X-HTTP-Method-Override Delete Action
[HttpDeleteLocalized]
public virtual ActionResult Edit_Editer(TId id, TSeq seq, TEntity editEntity)
{
...
}

cshtm Button:

<input type="submit" name="X-HTTP-Method-Override" value="@GlobalResources.Delete" formnovalidate="" class="btn btn-default" onclick="return confirmDelete('@GlobalResources.PromptBeforeDelete')" />
RitchieD
  • 1,831
  • 22
  • 21