MVC Skip IDs Separated by a + in Action

I want to be able to access the action at the following URL type:

http: // localhost / MyControllerName / MyActionName / Id1 + Id2 + Id3 + Id4 , etc.

and process it in code as follows:

public ActionResult MyActionName(string[] ids) { return View(ids); } 
+6
source share
2 answers

In the end, they chose the following solution:

  public ActionResult Action(string id = "") { var ids = ParseIds(id); return View(ids); } private static int[] ParseIds(string idsString) { idsString = idsString ?? string.Empty; var idsStrings = idsString.Split(new[] { ' ', '+' }); var ids = new List<int>(); foreach (var idString in idsStrings) { int id; if (!int.TryParse(idString, out id)) continue; if (!ids.Contains(id)) ids.Add(id); } return ids.ToArray(); } 
0
source

+ is a reserved character in the URL. This means a space. Thus, in order to achieve what you are looking for, you can write your own connecting device:

 public class StringModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (value != null && !string.IsNullOrEmpty(value.AttemptedValue)) { return value.AttemptedValue.Split(' '); } return base.BindModel(controllerContext, bindingContext); } } 

and then either register it globally for type string[] , or use the ModelBinder attribute:

 public ActionResult MyActionName( [ModelBinder(typeof(StringModelBinder))] string[] ids ) { return View(ids); } 

Obviously, if you want to use the URL of the form /MyControllerName/MyActionName/Id1+Id2+Id3+Id4 , which will bind the last part as an action parameter with the name ids , you will have to change the default route definition using {id} .

+8
source

Source: https://habr.com/ru/post/904434/


All Articles