使用ASP.NET MVC 3型号标识路径ID值路径、标识、型号、NET

2023-09-06 06:52:17 作者:离人少年昨与晨

场景 路线:/模板/自定义/ 10 其中:10 =模板的ID()

Scenario Route: /template/customize/10 Where: 10 = ID of Template()

在控制器基于该模型创建的模板,以便查看模型实际上是一个自定义()对象,它实际上为0的ID,因为它是新的。

In the controller the model is created based on the template so that the View's model is actually a Customization() object which actually has an Id of 0 because it's new.

在我渲染视图@ Html.HiddenFor(M => m.Id),得到的值,隐藏输入的是 10 ,但它应该是 0 因为m是类型定制的。我以前用MVC 2运行到这一点,并努力解决它通过不使用辅助方法。

In the view I render @Html.HiddenFor( m => m.Id ) and the resulting value of that hidden input is 10, though it should be 0 because m is of type Customization. I've run into this before with MVC 2 and worked around it by not using helper methods.

问题

有没有标注什么的我 可以添加到HTML辅助方法 实际呈现正确的价值?

Is there annotation or something I can add to the Html Helper method to actually render the correct value?

这是一个bug(MVC似乎是 渲染m.Id作为路由值 无论什么样的实际模型 被设置为在控制器)?

Is this a bug (MVC seems to be rendering m.Id as the route value regardless of what the actual model is set to in the controller)?

其他code澄清

查看

@model Project.Core.Domain.Customization
@using( Html.BeginForm( "save", "customization" ) )
{
    @Html.HiddenFor( m => m.Id )
    @Html.HiddenFor( m => m.Template.Id )
    <button type="submit" id="save" name="save">Save</button>
}

控制器

       public ActionResult Customize( int id )
    {
        var template = Persistence.Data.RetrieveObject<Template>( id );
        var model = new Customization();

        ViewBag.Template = template;
        return ( View( model ) );
    }

解决方案

行动改变签名:

public ActionResult Customize( int TemplateId ){ ... }

变更链接到行动,例如:

Changed link to action as such:

@Html.ActionLink( "customize", "customize", new { TemplateId = template.Id } )

我结束了一个网址,看起来像

I end up with a url that looks like

/template/customize?TemplateId=10

这是丑陋的,但我得到与model.Id保持我的观点干净,所以这是一个双赢的我。

It's uglier, but I get to keep my view clean with model.Id so this is a win for me.

推荐答案

我觉得这是因为当你使用类似 @ Html.HiddenFor(M =&GT; m.Id)的HTML辅助看看在不同的地方填充输入的值,并在路线中的值是那些地方之一。

I think this is because when you use something like @Html.HiddenFor( m => m.Id ) the html helpers look in various places to populate the input's value, and the values in the route is one of those places.

所以,你既可以改变你的路线,这样它的东西,像模板/自定义/ {TemplateId} ,然后让你的操作方法反映了这一点,如: 公众的ActionResult自定义(INT templateId)

So you could either change your route so that it's something like template/customize/{TemplateId} and then have your action method reflect this, e.g. public ActionResult Customize(int templateId).

或者你可以改变你的视图模型(或创建一个自定义视图模型),有一个 CustomizationId 属性,而不是仅仅编号

OR you could change your viewmodel (or create a custom view model) that has a CustomizationId property rather than just Id.

和不,这不是一个错误......它更可以带来无法预料的后果功能。但是,一旦你意识到这一点,它就像一种享受。

And no, it's not a bug... it's more of a feature that can have unforeseen consequences. But once you're aware of it, it works like a treat.

 
精彩推荐
图片推荐