【问题标题】:How to pass collection data through form?如何通过表单传递集合数据?
【发布时间】:2019-10-03 00:29:41
【问题描述】:

我正在.net core mvc 中编写一个简单的应用程序。 问题在于按视图加载相关数据。我第一次加载它通过美妙的视图时,我通过实体框架将数据附加到视图,包括扩展功能等。

此代码在 GET 上,仅显示要更新的项目时,用当前值填充字段。

public IActionResult Edit(long id)
        {
            ServiceResult<LectureDTO> result = _lectureService.GetById(id, new LectureIncludeOptions(true));
            LectureEditViewModel model = new LectureEditViewModel
            {
                Lecture = new LectureEditDTO(result.Entity)
            };
            if (!result.Success)
            {
                model.HandleResult(result, ModelState);
            }
            return View(model);
        }

第二次提交 POST 时,如果我提交的模型无效或更新结果不正确,我只想将错误附加到模型并将其发送到视图(通过HandleResult 方法)。

public IActionResult Edit(LectureEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ServiceResult<LectureDTO> getResult = _lectureService.GetById(model.Lecture.Id, new LectureIncludeOptions(true));
                if (!getResult.Success) 
                {
                    model.HandleResult(getResult, ModelState);
                }
                model.Lecture = new LectureEditDTO(getResult.Entity);
                return View(model);
            }

            ServiceResult<LectureDTO> result = _lectureService.Update(model.Lecture, User.FindFirstValue(ClaimTypes.NameIdentifier));
            if (result.Success)
            {
                model = new LectureEditViewModel()
                {
                    Lecture = new LectureEditDTO(result.Entity)
                };
            }
            model.HandleResult(result, ModelState);
            return View(model);
        }

这就是我目前在不良编辑时加载关系数据的方式。如果我之前已经在模型中拥有它,我认为这很浪费,只是显示编辑表单。有没有办法按模型传递这些数据?

我已经在我的表单中尝试过这个来传递集合,但是每次我调试这个控制器操作时,它的值都是空的。

<input asp-for="Lecture.Lecturers" value="@Model.Lecture.Lecturers" class="form-control" type="hidden" />

我做错了吗?我一直在做的事情好吗?我可以改进什么?

感谢您花时间帮助我。

【问题讨论】:

  • 首先,您不能对整个数据集合使用单一输入。您需要遍历您的集合并为每个项目的每个属性枚举一个输入。其次,你不需要为错误做任何特别的事情。 ModelState 涵盖了这个。
  • 好吧,那基本上还是为他们再查询一次db就好了,而不是添加这么多的隐藏字段?这基本上就是我在 Handle 方法中所做的,如果它们属于那种性质,我会将所有来自结果的消息作为错误附加到状态:)
  • 是的。确实。您永远不应该发布任何您不希望用户能够更改的内容。应始终要求支持数据集。
  • 谢谢,担心我做错了什么。

标签: c# asp.net-core-mvc


【解决方案1】:

正如 Chris Pratt 在对我的线程的评论中指出的那样,您不应该将任何数据发布到服务器,您不希望用户能够更改。因此,我以这种方式使用集合的情况是无效的。要将集合发布到服务器,请将它们写在输入字段中并发布。

【讨论】:

    猜你喜欢
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多