asp.net-mvc – 模型绑定不起作用

我有以下POCO课程:
public class Location
    {
        public int LocationId { get; set; }
        public string Name { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
        public string Country { get; set; }
        public float? Latitude { get; set; }
        public float? Longitude { get; set; }
        public string PhoneNumber { get; set; }
        public string EmailAddress { get; set; }
        public string Website { get; set; }
        public virtual ICollection<Program> Programs { get; set; }
        public virtual ICollection<PlayerType> PlayerTypes { get; set; }
    }

public class PlayerType
    {
        public int PlayerTypeId { get; set; }
        public string Name { get; set; }
        public int SortOrder { get; set; }
        public bool IsActive { get; set; }
        public virtual ICollection<Location> Locations { get; set; }
    }

和视图模型类

public class Locationviewmodel
    {
        public Location Location { get; set; }
        public IList<PlayerType> SelectPlayerTypes { get; set; } 

        public Locationviewmodel()
        {
            Location = new Location();
        }

    }

在我的创建表单中,我已将模型定义为

@model Locator.Models.Locationviewmodel

并有以下字段:

div class="editor-label">
    @Html.LabelFor(model => model.Location.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Location.Name)
    @Html.ValidationMessageFor(model => model.Location.Name)
</div>

在我的控制器中处理我的POST

[HttpPost]
        public ActionResult Create(Locationviewmodel location)
        {
            if (ModelState.IsValid) {
                locationRepository.InsertOrUpdate(location.Location);
                locationRepository.Save();
                return RedirectToAction("Index");
            }
            location.SelectPlayerTypes = golferTypeRepository.All.Where(p => p.IsActive).ToList();
            return View(location);
        }

问题是我有一个Location对象,但没有任何属性设置为在表单中输入的值.

在这里做错了吗?

谢谢

解决方法

这是问题所在:
[HttpPost]
public ActionResult Create(Locationviewmodel location)

你看到了吗?它是您的动作参数的名称:位置.

现在看一下你的视图模型,它有一个名为Location的属性

public Location Location { get; set; }

这会混淆模型绑定器.它不再知道您是否需要绑定Locationviewmodel或其属性.

所以只需重命名以避免冲突:

[HttpPost]
public ActionResult Create(Locationviewmodel model)

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....