【问题标题】:Asp.net MVC View Textbox Returns Default ValueAsp.net MVC 查看文本框返回默认值
【发布时间】:2015-09-02 06:57:20
【问题描述】:

我可以将纬度、经度、邻居和邻居限制变量发送到 View。但是,我想从视图中更改邻居限制。当我发布 View 时,MapViewModel 的变量为 0,我试过 ModelState.Clear() 但没有区别,你能帮我吗?谢谢

型号:

public class MapViewModel
{
    public double lat;
    public double lon;
    public List<Point> neighbors;
    public Polygon polygon;

    public int neighborlimit;
    public double[][] polyTable;
}

控制器:

    [HttpGet]
    public ActionResult Map()
    {
        UserAccount user = (UserAccount)UserManager.FindByName(User.Identity.Name);
        MapViewModel model = new MapViewModel() { lat = (double)user.address.latitude, lon = (double)user.address.longitude, neighbors = user.getNeighbors(), neighborlimit= (int)user.neighborsLimit };
        return View(model);
    }

    [HttpPost]
    public ActionResult Map(MapViewModel model)
    {
       UserAccount user = (UserAccount)UserManager.FindByName(User.Identity.Name);         
       user.neighborsLimit = model.neighborlimit;
       UserManager.Update(user);
       return View(model); 
    }

查看:

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

    <div class="form-group">
        <div class="col-md-10">
            @Html.TextBoxFor(h => h.neighborlimit, new { @class = "form-control" })
          </div>
           <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Log in" class="btn btn-default" />
                </div>
            </div>
}

【问题讨论】:

    标签: asp.net-mvc razor http-post


    【解决方案1】:

    您没有neighborlimit 的属性(只是一个字段)。改成

    public int neighborlimit { get; set; }
    

    这将允许DefaultModelBinder 在您提交表单时设置属性

    【讨论】:

    • 谢谢,它可以工作,但我现在有另一个问题,UserManager.Update(user) 不会更改数据库中的值,我遇到了一个错误,'System.Data.Entity.Validation 类型的异常.DbEntityValidationException' 发生在 mscorlib.dll 中,但未在用户代码中处理 你知道吗?
    • 我不知道你的 UserManager.Update(user); 函数是做什么的。您将需要提出一个新问题,其中包含详细信息,包括错误消息
    【解决方案2】:

    问题在于表单中没有值,这就是为什么在发布表单时值不存在并且 ModelBinder 设置默认值的原因。如果安全性不是问题,而是您想要保留的所有值的隐藏字段。

    类似的东西

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(h => h.lat)
        /* Now enter hidden fields for all of the properties that you want */
    
        <div class="form-group">
            <div class="col-md-10">
                 @Html.TextBoxFor(h => h.neighborlimit, new { @class = "form-control" })
            </div>
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Log in" class="btn btn-default" />
            </div>
        </div>
    }
    

    更新

    正如 Stephen Muecke 所说,确保使用属性而不是字段

    【讨论】:

    • 我试过了,但是值仍然是0,当我发布时,值是0,可以查看,其余的都是Null,这有意义吗?例如; lat=0 lon=0 neighborlimit=0 polygon=Null polyTable=Null
    • 正如@Stephen Muecke 所说,您应该将其从字段更改为属性。我没有看到您使用的是字段而不是属性
    猜你喜欢
    • 2011-08-30
    • 2017-01-15
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2013-01-31
    • 1970-01-01
    相关资源
    最近更新 更多