【问题标题】:C# ASP MVC Route Model ID bugC# ASP MVC 路由模型 ID 错误
【发布时间】:2021-03-17 07:14:46
【问题描述】:

你能解释一下如何解决 dotnet 中视图模型被路由绑定覆盖的错误吗? 因为视图显示路由 ID 而实际 ID 被丢弃。我尝试调试,但它看起来不错,但在呈现值后它仍然显示 URL 值而不是 MODEL 值。

路由

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 }
  );
}

型号

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

    }
}

控制器

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

查看

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

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

输出http://localhostHome/Index/1

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

预期

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

【问题讨论】:

  • @Html.HiddenFor(m =&gt; m.Id, new { @Value = Model.Id }
  • @Mertuarez:对于这种情况,最简单的方法是更改​​操作方法参数名称。例如,public ActionResult Index(int? idd)
  • @Mertuarez:或者您可以提供自己的默认模型绑定器 ModelBinders.Binders.DefaultBinder 并实现所需的逻辑。

标签: c# asp.net .net asp.net-mvc asp.net-mvc-3


【解决方案1】:

据我所知,这个问题的答案是从模型状态中删除密钥。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2012-10-27
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多