简体   繁体   English

ViewModel回传null

[英]ViewModel posting back null

I have a view model that contains two models, one is a IList: 我有一个包含两个模型的视图模型,一个是IList:

public class PersonViewModel
{
   public Person person { get; set; }
   public IList<Snack> { get; set; }
}

This outputs all of the data I need for my main view and partial view just fine. 这样就输出了我的主视图和局部视图所需的所有数据。 The problem I'm having is when I hit my action that is tied to the submit button. 我遇到的问题是当我点击与“提交”按钮相关的动作时。

 @using (Html.BeginForm("ProcessSnacks", "Person", FormMethod.Post))
 {
     <input id="process" type="submit" value="Process Snacks" />
 }

On my controller I have: 在我的控制器上,我有:

public ActionResult ProcessSnacks(PersonViewModel vm)
{     
   //ViewModel is NULL here...
}

I actually just need the data from the Person model inside the PersonViewModel and have tried many permutations... I've tried just having person as the parameter instead of the view model but no luck. 实际上,我实际上只需要PersonViewModel内部的Person模型中的数据,并尝试了许多排列...我试图仅将person作为参数而不是视图模型,但是没有运气。 I've been all over StackOverflow as well and can't seem to find another issue that quite matches. 我也已经遍及StackOverflow,似乎找不到另一个完全匹配的问题。

You just tied viewmodel to the view on the server-side, but the view itself doesn't use the data in any way, so when you submit it, client-side can't possibly know that you want the some data posted back to the server. 您只是将viewmodel绑定到服务器端的视图,但是视图本身不以任何方式使用数据,因此在提交数据时,客户端可能无法知道您是否希望将一些数据回传到服务器。 If you want such behaviour, you need to have some fields inside your form, that would make it possible to send the data back to the server. 如果您想要这种行为,则需要在表单中包含一些字段,这样就可以将数据发送回服务器。

You must understand, posting back in MVC isn't some miracle, most work is done for you though (binding for instance), but you have to provide bare minimum for it to work. 您必须了解,在MVC中发回邮件并不是什么奇迹,尽管大多数工作都为您完成(例如绑定),但是您必须提供最低限度的工作。 If you don't want to have a form with textboxes, you can use for instance @Html.HiddenFor(...) helper for all fields you need to post to server. 如果您不希望使用带有文本框的表单,则可以使用@Html.HiddenFor(...)帮助程序来处理需要发布到服务器的所有字段。

Please note that even though hidden fields aren't visible in browser, they are visible and editable (if you know how), so it is not safe to pass some data that need to be protected from the user. 请注意,即使隐藏字段在浏览器中不可见,但它们是可见且可编辑的(如果您知道如何),因此传递某些需要保护免受用户访问的数据并不安全。

Put in some textforms/dropdowns or hiddentextboxes on the view with your model as the values, you should then see it on the post back. 将视图作为模型的值放在视图中的某些文本形式/下拉列表或隐藏的文本框中,然后应在回发中看到它。

As it stands your view doesn't contain any model values hence on postback it will be blank. 就目前而言,您的视图不包含任何模型值,因此在回发时它将为空白。

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

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