C#ASP MVC路由模型ID错误 [英] C# ASP MVC Route Model ID bug

查看:299
本文介绍了C#ASP MVC路由模型ID错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

路由

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

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

推荐答案

据我发现,为此问题的答案是从modelstate中删除密钥.

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-[Bind(Exclude ="Id";)]

这篇关于C#ASP MVC路由模型ID错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆