将模型从视图传递到控制器 [英] Pass Model from View to Controller

查看:79
本文介绍了将模型从视图传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将模型传递给控制器​​的Post方法.调用method时,对于内容显示null值,对于ID显示0.理想情况下,它应该包含已显示的模型的值.

I want to pass model to Post method of controller. When method is called it shows null value for content and 0 for Id. Ideally it should contain the values of model it has displayed.

查看:

@model MvcApplication4.Models.WorldModel
@{
    ViewBag.Title = "Information";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("Information", "World", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <br />
    @Html.DisplayFor(model => model.Id)
    <br />
    @Html.DisplayFor(model => model.Content)
    <br />
    <input type="submit" value="Next" />
}

控制器:单击提交按钮时调用的方法.

Controller: Method called when click on submit button.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Information(WorldModel worldModel)
        {
            CandidateSession cs = (CandidateSession)Session["Can"];
            var can = cs.Candidates.Where(x => x.IsNameDispalyed == false);
            if (can.Count() > 0)
            {
                var can1 = can.First();
                can1.IsNameDispalyed = true;
                Session["Can"] = cs;
                return View(new WorldModel() { Id = can1.Id, Content = can1.Name });
            }
            return View(new WorldModel());
        }

型号:

public class WorldModel
    {
        public int Id { get; set; }

        public string Content { get; set; }
    }

推荐答案

您应添加包含您的值的隐藏输入:

You should add hidden inputs containing your values :

@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Content)

这是因为模型绑定程序将搜索输入(例如文本框或隐藏字段)以获取值并将它们与模型属性相关联(基于输入名称). DisplayFor不会创建任何输入,因此在提交表单时,模型绑定程序找不到您的值.

This is because the model binder will search for inputs (like textboxes, or hidden fields) to get values and associated them with your model properties (based on input names). No input is created with DisplayFor, so the model binder can't find your values when you submit your form.

这篇关于将模型从视图传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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