0

Can you explain me how to solve bug in dotnet where view model is override by routing binding? Because view is showing routing ID and actual ID is discarded. I try to debug but it looks good but after rendering of value it show still URL value and not MODEL value.

Routing

public static void RegisterRoutes(RouteCollection routes)
{
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
   name: "Default",
    url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );
}

Model

namespace Test.Models
{
    public class HomeIndex
    {
        public int Id { get; set; }

    }
}

Controller

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            var model = new Models.HomeIndex()
            {
                Id = 65
            };
            
            return View(model);
        }       
    }
}

View

@model Test.Models.HomeIndex
@{
    ViewBag.Title = "Home Page";
}

@Html.HiddenFor(x => x.Id)
@Html.DisplayFor(x => x.Id)
@Html.EditorFor(x => x.Id)

Output http://localhostHome/Index/1

<input id="Id" name="Id" type="hidden" value="1" />
65
<input id="Id" name="Id" type="number" value="1" />

Expected

<input id="Id" name="Id" type="hidden" value="65" />
65
<input id="Id" name="Id" type="number" value="65" />
Mertuarez
  • 901
  • 7
  • 24
  • 1
    `@Html.HiddenFor(m => m.Id, new { @Value = Model.Id }` – Chetan Dec 05 '20 at 13:57
  • @Mertuarez: For this case the easiest way is just change the action method parameter name. For example, `public ActionResult Index(int? idd)`. – Jackdaw Dec 07 '20 at 16:54
  • @Mertuarez: Or you can provide you own the **default model binder** `ModelBinders.Binders.DefaultBinder` and implement required logic. – Jackdaw Dec 07 '20 at 23:59

1 Answers1

0

So far as i found as an answer for this issue is remove key from modelstate.

[HttpGet] // http://localhost/Home/Detail/1
public ActionResult Detail(int? Id)
{
    ModelState.Remove(nameof(Id)); // this will remove binding
    var model = new Models.HomeIndex()
    {
        Id = 65
    };
        
    return View(model);
}



[HttpPost] // http://localhost/Home/Detail/
public ActionResult Detail(Models.HomeIndex model)
{
   if (ModelState.IsValid)
    {
        //...
        return RedirectToAction("Index");
    }
    return View(model);
}

ASP.NET MVC - Alternative for [Bind(Exclude = "Id")]

Mertuarez
  • 901
  • 7
  • 24