为什么比规定的其他模型属性@ Html.HiddenFor设定值? [英] Why do @Html.HiddenFor set value for other model property than specified?

查看:454
本文介绍了为什么比规定的其他模型属性@ Html.HiddenFor设定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作在哪里,我定义如下模型ASP.NET MVC3项目:

I'm working on a ASP.NET MVC3 project where I've defined the following model:

public class Model{
    [Key]
    int Id { get; set; }
    int MappedId { get; set; }
}

该模型是从控制器到的Razor视图过去了,如下:

This model is passed from a Controller to a Razor view, as follows:

public class Controller:Controller{
    public ActionResult Edit(int id) {
        Model model = repository.Get(id);
        return View(model);
    }
}

模型属性在视图中呈现:

The model properties are rendered in the view:

@using(Html.BeginForm()) {
    @Html.HiddenFor(model => model.Id);
    @Html.HiddenFor(model => model.MappedId)
}

有什么奇怪的是,两个隐藏的投入得到相同的值,即使模特属性传递给视图的时候有不同的价值观。例如。如果Model.Id具有值0和Model.MappedChannelId已经值7,两个隐藏的输入被设定为相同的值7:

What's strange is that the both the hidden inputs get the same value, even though the model properties have different values when passed to the View. E.g. if the Model.Id has value 0 and Model.MappedChannelId have value 7, both hidden inputs are set to the same value 7:

<input id="Id" class="valid" type="hidden" value="7" name="Id" data-val-required="The Id field is required." data-val-number="The field Id must be a number." data-val="true">
<input id="MappedId" class="valid" type="hidden" value="7" name="MappedId" data-val-required="The MappedId field is required." data-val-number="The field MappedId must be a number." data-val="true">

有没有人有,为什么Html.HiddenFor(型号=> model.Id)​​的值设置为相同的值model.MappedId一个想法,即使传递到时查看model.Id有不同的价值?

Does anyone have an idea about why Html.HiddenFor(model=> model.Id) set the value to the same value as model.MappedId, even if model.Id has a different value when passed to the View?

推荐答案

我的猜测是,你从你的行为的id参数的值MappedId。然后,设置一些其他值ID属性。然而,在你看来,你还是得从操作参数和默认模型绑定Id值用来绑定Id属性该值。它基本上忽略来自模型实例的值。

My guess is you get the MappedId value from the id parameter of your action. Then you set the Id property with some other value. However in your view you still have Id value from the action parameter and default model binder uses that value for binding Id property. It basically ignores the value from the model instance.

您可以通过在模式转变id属性的名称解决它。如果你不希望出现这种情况,你应该改变操作参数的名称。然而,你需要为它创建一个自定义的路线,如果你不想通过查询字符串传递其价值。

You can solve it by changing the name of Id property in your model. If you don't want that, you should change the name of the action parameter. However you need to create a custom route for it if you don't want to pass its value by querystring.

这篇关于为什么比规定的其他模型属性@ Html.HiddenFor设定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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