ASP.NET MVC 3 Model Id using Route Id value

后端 未结 3 1714
执笔经年
执笔经年 2020-12-20 20:27

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

In the controller the model is created based on the template so that the Vie

相关标签:
3条回答
  • 2020-12-20 20:36

    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.

    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).

    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.

    0 讨论(0)
  • 2020-12-20 20:53

    You can always choose not to use the HTML Helper in this case and use plain HTML instead:

    <input name="Id" id="Id" type="hidden" value="@Model.Id"/>

    0 讨论(0)
  • 2020-12-20 20:53

    To prevent route values from overriding the model's corresponding properties, call ModelState.Clear() in your controller action. Be careful to call this method after using/reading the model state.

    public ActionResult Customize( int id )
    {
        var template = Persistence.Data.RetrieveObject<Template>( id );
        var model = new Customization();
    
        ViewBag.Template = template;
    
        this.ViewData.ModelState.Clear(); // add that after you consume the ModelState
        return ( View( model ) );
    }
    

    On my side, the hidden input gets the model's value instead of the route value.

    0 讨论(0)
提交回复
热议问题