C# ASP MVC Route Model ID bug

与世无争的帅哥 提交于 2020-12-15 03:42:39

问题


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" />

回答1:


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")]



来源:https://stackoverflow.com/questions/65157035/c-sharp-asp-mvc-route-model-id-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!