Asp.net MVC视图文本框返回默认值

时间:2015-09-02 06:57:21

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

我可以将lat,lon,neighbors和neighborslimit变量发送给View.Yet,我想从视图中更改neighborlimit。当我发布View时,MapViewModel的变量为0,我试过ModelState.Clear()但是没有区别,你能帮我解决一下吗?感谢

MODEL:

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>
}

2 个答案:

答案 0 :(得分:1)

您没有neighborlimit的属性(只是一个字段)。将其更改为

public int neighborlimit { get; set; }

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

答案 1 :(得分:0)

问题在于,您没有表单中的值,这就是为什么在发布表单时值不存在且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 所说,请确保使用的属性不是字段