如何使用 POST 将复杂对象从视图传递到控制器 - ASP.NET MVC [英] How can i pass complex object from view to controller with POST - ASP.NET MVC

查看:69
本文介绍了如何使用 POST 将复杂对象从视图传递到控制器 - ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到解决我的问题的方法,但我不能.我有一堂课,有一篇论文和很多关键词

Hi i tried to find a fix to my problem but i cant. I have a class with one Thesis and many keywords

public class ThesisWithKeywordsModel
    {
        public Thesis thesis { get; set; }
        public IQueryable<Keyword> keywords { get; set; }
        public IEnumerable<int> checkboxList { get; set; }
    }

行动

        [HttpGet]
        public ActionResult CreateThesis()
        {
            ThesisWithKeywordsModel thesis = new ThesisWithKeywordsModel();
            thesis.thesis = new Thesis();
            thesis.keywords = db.KeywordRepository.GetAllKeywords();
            thesis.checkboxList = new List<int>();
            return View(thesis);
        }

在哪里我使用 thesis.keywords 来显示复选框按钮列表,我把 thesis.checkboxList 保存从视图返回的结果谁必须是 ICollection(int) id 来自选中的复选框按钮.

where I use thesis.keywords to show list of checkbox buttons and I put thesis.checkboxList to save returned result from view who must be ICollection(int) id's from checked checkbox buttons.

这是我的观点

@model SearchSystem.Models.ThesisWithKeywordsModel

@{
    var listField = new List<SelectListItem>();
    listField.Add(new SelectListItem() { Text = "Софтуер", Value = "Софтуер", Selected = true });
    listField.Add(new SelectListItem() { Text = "Хардуер", Value = "Хардуер" });
    listField.Add(new SelectListItem() { Text = "Мрежи", Value = "Мрежи" });

    var listFree = new List<SelectListItem>();
    listFree.Add(new SelectListItem() { Text = "Свободна", Value = "Свободна", Selected = true });
    listFree.Add(new SelectListItem() { Text = "Заета", Value = "Заета" });
}

@using (Html.BeginForm("CreateThesis", "ProfessorProfile", FormMethod.Post))
{
     <table class="table">
        <tr>
            <td>@Html.LabelFor(x => x.thesis.ThesisTitle)</td>
            <td>@Html.EditorFor(x => x.thesis.ThesisTitle)</td>  
        </tr>
        <tr>
             <td>@Html.LabelFor(x => x.thesis.ThesisDescription)</td>
             <td>@Html.EditorFor(x => x.thesis.ThesisDescription)</td>
        </tr>
        <tr>
             <td>@Html.LabelFor(x => x.thesis.Field)</td>
             <td>@Html.DropDownList("Field", listField)</td>
        </tr>
         <!--<tr>
             <td>@Html.LabelFor(x => x.thesis.Free)</td>
             <td>@Html.DropDownList("Free", listFree)</td>
         </tr>-->
    </table>

    foreach(var keyword in Model.keywords)
    {
        <input type="checkbox" id="@keyword.KeywordId" name="checkboxList" value="@keyword.KeywordId">
        <label for="@keyword.KeywordId">@keyword.Value</label><br/>
    }

    <input type="submit" value="Create"/>
}

这是我的另一个动作

[HttpPost]
        public ActionResult CreateThesis(ThesisWithKeywordsModel thesis)
        {
            if (ModelState.IsValid)
            {
                var loggedProfessorId = db.ProfessorRepository.GetProfessorIDByUserName(User.Identity.Name);
                if (loggedProfessorId != 0)
                {
                    var professor = db.ProfessorRepository.GetProfessorById(loggedProfessorId);
                    db.ProfessorRepository.AddThesis(professor, thesis.thesis);
                    return RedirectToAction("MyTheses");
                }
                return RedirectToAction("Login", "Account");
            }
            return View(thesis);
        }

问题是对象ThesisWithKeywordsModel thesis 为空,thesis.thesis,thesis.checkboxList 都为空.有趣的是,当我在响应正文中看到响应时,我有 POST 参数,如果我将 ThesisWithKeywordsModel thesis 更改为 Thesis thesis,我将拥有我从表单发布的所有值.>

The problem is the object ThesisWithKeywordsModel thesis is null, thesis.thesis, thesis.checkboxList are both null. Funny thing is that when i see response in response body I have POST parameters and if I change ThesisWithKeywordsModel thesis with Thesis thesis i have all values that i post from form.

推荐答案

首先,我不会尝试将 IQueryable 用于 Keywords 属性,最好使用 IList.其次,将关键字和 CheckboxList 组合成一个属性可能会更好,让您的关键字类是这样的:

Firstly I would not attempt to use IQueryable for your Keywords property, better would be to use IList. Secondly it would probably be better to combine Keywords and CheckboxList into a single property, having your keyword class something like this:

public class Keyword
{
    public int KeywordId {get;set;}
    public bool Checked {get;set;}
}

所以 ThesisWithKeywordsModel 看起来像这样:

So ThesisWithKeywordsModel would look like this:

public class ThesisWithKeywordsModel
{
    public Thesis thesis { get; set; }
    public IList<Keyword> keywords { get; set; }
}

然后在您的控制器中,您应该能够:

Then in your controller, you should be able to do:

thesis.keywords = db.KeywordRepository.GetAllKeywords()
                     .Select(kw => new Keyword
                     {
                        KeyeordId = kw.KeywordId,
                        Checked = false
                     }).ToList();

接下来,当将值列表传入/传出视图时,您需要将 cshtml 中的 foreach 循环更改为 for 循环.

Next you need to change your foreach loop in the cshtml into a for loop when passing a list of values to/from the view.

for(var i = 0; i < Model.keywords.Count; i++)
{
    <input type="checkbox" id="@Model.keywords[i].KeywordId" name="checkboxList" checked='@Model.keywords[i].Checked ? "checked" : ""'>
    <label for="@Model.keywords[i].KeywordId">@Model.keywords[i].Value</label><br/>
}

这篇关于如何使用 POST 将复杂对象从视图传递到控制器 - ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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