简体   繁体   English

将ViewModel从HttpGet Action传递给HttpPost Action

[英]Pass ViewModel from HttpGet Action to HttpPost Action

I'm trying to initialize a ViewModel in my Action Get then pass it to View, use some data, then get all that data back to use in my Action Post like this: 我正在尝试在我的Action中初始化ViewModel然后将其传递给View,使用一些数据,然后将所有数据重新用于我的Action Post中,如下所示:

ViewModel: 视图模型:

public class AddResponseModel
    {
        iDeskEntities db = new iDeskEntities();
        public AddResponseModel()
        {
            RespTypeList = new SelectList(db.ResponseType.Where(e=>e.type != "Assignar" && e.type != "Reabrir"), "type", "type");
            newRespList = new SelectList(db.Users, "id", "name");
        }

        [Required]
        [DataType(DataType.Text)]
        public string response { get; set; }

        [HiddenInput]
        public Requests request { get; set; }

        [HiddenInput]
        public string newResp { get; set; }

        [DataType(DataType.Text)]
        public SelectList newRespList { get; set; }

        [HiddenInput]
        public int RespType { get; set; }

        [Required]
        [DataType(DataType.Text)]
        public SelectList RespTypeList { get; set; }
    }

Controller: 控制器:

[HttpGet]
        public ActionResult AddResponse(int? id)
        {
            AddResponseModel model = new AddResponseModel();
            model.request = db.Requests.Find(id);
            return View("AddResponse", model);
        }

[HttpPost]
        public ActionResult AddResponse(Requests req, AddResponseModel model)
        {
            //Some code, where i wanna access again model.request that i //initiated on the GET action
            return RedirectToAction("Dashboard", "BHome");
        }

View: 视图:

@using (Html.BeginForm("AddResponse", "Requests", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true)

        @if (Model.request.state != 0)
        {
            <div class="form-group">
                @Html.LabelFor(model => model.RespType, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.RespType, Model.RespTypeList)
                    @Html.ValidationMessageFor(model => model.RespType)
                </div>
            </div>
        }

        <div class="form-group">
            @Html.LabelFor(model => model.response, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.response)
                @Html.ValidationMessageFor(model => model.response)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Adicionar Resposta" class="btn btn-default" />
            </div>
        </div>
    </div>
}

Is there anyway to do it? 无论如何要做到这一点? Because when I try to use the "model.request" in the Post method he comes "null" 因为当我尝试在Post方法中使用“model.request”时,他会出现“null”

Binding will only occur for fields that are actually used. 绑定仅适用于实际使用的字段。 If you are not using the request property in your view, might be better to just have the ID in a hidden input and load again on server in your POST. 如果您未在视图中使用请求属性,可能最好只将ID保存在隐藏的输入中,然后再次在POST的服务器上加载。 For the state, just add bool property to your model. 对于州,只需将bool属性添加到模型中即可。

You can't bind a single field like a hidden input to an entire object. 您不能将像隐藏输入这样的单个字段绑定到整个对象。 If you pass it the object, it's just going to call ToString on it to get a representation, which will most likely end up being something like "{Namespace.To.Requests}" , rather than the actual data contained within that object. 如果你将对象传递给它,它就会调用ToString来获取一个表示,这很可能最终会像"{Namespace.To.Requests}" ,而不是该对象中包含的实际数据。

You can either explicitly create inputs for each property of the object, ie: 您可以为对象的每个属性显式创建输入,即:

@Html.HiddenFor(m => m.request.Foo)
@Html.HiddenFor(m => m.request.Bar)
@Html.HiddenFor(m => m.request.Baz)

Or you can use EditorFor to let MVC do this for you by convention: 或者您可以使用EditorFor让MVC EditorFor为您执行此操作:

@Html.EditorFor(m => m.request)

When fed an entire object, EditorFor will actually dig in and generate fields for each public property on that object according to the information it can get from the class, such as the property type and attributes applied ( DataType , UIHint , etc.) 当馈送整个对象时, EditorFor将根据它从类中获取的信息(例如应用的属性类型和属性( DataTypeUIHint等))实际挖掘并为该对象上的每个公共属性生成字段。

That means, it likely won't choose hidden fields. 这意味着,它可能不会选择隐藏的字段。 You could annotate the properties in the class with the HiddenInput attribute: 您可以使用HiddenInput属性注释类中的属性:

[HiddenInput]
public string Foo { get; set; }

However, you wouldn't want to do that on something like an entity class, since it will effect every use of this class for a form. 但是,您不希望在类似实体类的内容上执行此操作,因为它会影响表的每个类的使用。 View models are often utilized in these cases as you can create a separate view model representing the entity for as many views as you need without effecting other areas of your application. 在这些情况下经常使用视图模型,因为您可以根据需要创建一个单独的视图模型来表示实体,而不会影响应用程序的其他区域。

You can also utilize editor templates to define the set of fields EditorFor should render for the object. 您还可以使用编辑器模板来定义EditorFor应为对象呈现的字段集。 By simply adding the view Views\\Shared\\EditorTemplates\\Requests.cshtml , whenever you call EditorFor with an instance of Requests , it will render that template. 只需添加视图Views\\Shared\\EditorTemplates\\Requests.cshtml ,无论何时使用Requests实例调用EditorFor ,它都将呈现该模板。 You could then, inside that view, render the fields for Requests any way you like. 然后,您可以在该视图中以任何方式呈现Requests的字段。 However, again, this is a global change that would affect any usage of EditorFor with an instance of Requests . 但是,这是一个全局变化,会影响任何使用Requests实例的EditorFor

More likely than not, your best bet is to simply manually call Html.HiddenFor for each property on the class as described above directly in your view. 更有可能的是,您最好的选择就是直接在视图中为上面的每个属性手动调用Html.HiddenFor

您可以将对象作为模型传递给视图,但是当您想要将对象的数据发送回控制器而无法发送对象时,您必须使用具有相同属性对象名称的原始变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM