c#asp.net:使用表单将元素添加到模型的列表中 [英] c# asp.net: add element to a list in a model using form
问题描述
很抱歉我的术语很差
但我会尽力向自己解释一下:
but I'll try to explain myself better:
-
给出一个包含obj和obj列表的模型
give a model that contains a list of obj and an obj
我希望视图中的表单将obj(和列表)发送给控制器
I want a form in my view to send the obj (and the list )to the controller
控制器,将obj添加到更新后的列表中并将其发送回视图.
the controller to add the obj to the updated list and send it back to the view.
我的问题是在提交时将初始"列表传递给表单;
my problem is passing the "initial" list to the form on submit;
这不起作用:
<div class="form-group">
@Html.HiddenFor(m => m.RequestList, Model.RequestList)
</div>
回答...
这个问题可能已经在这里得到答案:
This question may already have an answer here:
型号 模型绑定到列表MVC 4 3个答案
不,不是, 我不是要编辑列表,而不仅仅是声明", 无论如何,正如我所建议的,我试图循环列表中的元素并将其添加到新元素中";
no it isn't, I'm not trying to edit the list rather than just "declare it", anyway as suggested I'm trying to loop the elements in the list and "add it to the new one";
-
一些东西实际上传递给了模型,但是为空!
something get actually passed to the model, but is null!
for (int i = 0; i < Model.RequestList.Count(); ++i)
{
@Html.HiddenFor(m => m.RequestList[i], new {
StartTime = Model.RequestList[i].StartTime,
EndTime = Model.RequestList[i].EndTime,
StatusId = Model.RequestList[i].StatusId,
})
}
再次:我在做什么错了?
again: what am I doing wrong?
- I think this solution is actually closer to what I mean (sorry isn't stackoverflow)
但是尝试这样的事情
@using (Html.BeginForm("CreateComplex", null, FormMethod.Post, new { @class = "", RequestList = Model.RequestList}))
仍然不起作用
推荐答案
如果您不想使用数据库路由,则可以使用ViewBag
存储列表,然后使用System.Web.Helpers
中的Json
处理转化示例
If You don't want to use the database route, You can use ViewBag
to store the list and then Json
of System.Web.Helpers
to handle conversions example
您需要的视图
@{
var RequestList = (List<string>)ViewBag.RequestList;
}
//you are using a null controller here --gotten from question
@using (Html.BeginForm("CreateComplex", null, FormMethod.Post, new { @class = "" }))
{
<input type="hidden" name="RequestList" id="myHiddenInput" value="@Json.Encode(RequestList)" />
//other inputs that are binded to the model
}
控制器
[HttpPost]
public ActionResult CreateComplex(Model model, string RequestList)
{
var thelist = System.Web.Helpers.Json.Decode<List<string>>(RequestList);
thelist.Add(model.TheAttrForAddition);
//model.TheAttrForAddition is the attribute in the model the user is editing
ViewBag.RequestList= thelist;
//do other things and return the view
}
这篇关于c#asp.net:使用表单将元素添加到模型的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!