【发布时间】: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 => 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