[英]MVC Pass ViewBag to Controller
I have a Viewbag that is a list that I am passing from the Controller to the View. 我有一个Viewbag,它是我从Controller传递给View的列表。 The Viewbag is a list of 10 records in my case. Viewbag是我案例中的10条记录列表。 Once in the view, if the user clicks on save, I like to pass the content of the View to the [HttpPost] Create controller so that I can create records that are in the Viewbag. 进入视图后,如果用户点击了save,我想将View的内容传递给[HttpPost] Create控制器,以便我可以创建Viewbag中的记录。 I am on sure how to do this. 我确定如何做到这一点。 I have done the creation of a new record for 1 item but how do I do it for multiple records. 我已经为1个项目创建了一个新记录,但是如何为多个记录创建它。
Here is a quick example of using the ViewBag. 以下是使用ViewBag的快速示例。 I would recommend switching and using a model to do your binding. 我建议切换并使用模型进行绑定。 Here is a great article on it. 这是一篇很棒的文章。 Model Binding 模型绑定
Get Method: 获取方法:
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
List<string> items = new List<string>();
items.Add("Product1");
items.Add("Product2");
items.Add("Product3");
ViewBag.Items = items;
return View();
}
Post Method 发布方法
[HttpPost]
public ActionResult Index(FormCollection collection)
{
//only selected prodcuts will be in the collection
foreach (var product in collection)
{
}
return View();
}
Html: HTML:
@using (Html.BeginForm("Index", "Home"))
{
foreach (var p in ViewBag.Items)
{
<label for="@p">@p</label>
<input type="checkbox" name="@p" />
}
<div>
<input id='btnSubmit' type="submit" value='submit' />
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.