如何在 MVC 中发布项目列表 [英] How can I post a list of items in MVC

查看:35
本文介绍了如何在 MVC 中发布项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,其中包含一个项目列表,我想将它们发布到控制器,但有趣的是我不能.除了列表之外,其他所有内容都正常进行.我检查了 firebug 中的 ajax 调用,post 值是这样的:

Answers[0].IsMissing FalseAnswers[0].Text JaAnswers[0].Value 0答案[1].IsMissing FalseAnswers[1].Text Nein答案[1].值 1编号 1cd14b08-ce3b-4671-8cf8-1bcf69f12b2d姓名 Ja/Nein

我有一个具有以下属性的 AnwserScheme 类:

public string Name { get;放;}public bool IsMissing { get;放;}公共列表答案 { 得到;放;}公共答案方案(){Answers = new List();}

我有这个视图代码:

@for (int i = 0; i  Model.Answers[i].IsMissing)@Html.TextBoxFor(model => Model.Answers[i].Value,new { @class = "inputValue" })</td><td>@Html.TextBoxFor(model => Model.Answers[i].Text,new { @class = "inputAnswer" })</td><td><span class="span-delete"data-answer-scheme-id="@Model.Id"data-answer-id="@Model.Answers[i].Id" >x</span></td></tr>}

我有这段负责发帖的ajax代码:

$.ajax({url: "/AnswerScheme/AddAnswer",类型:帖子",数据:$("#formAnswerScheme").serialize(),成功:功能(数据){控制台日志(数据);$("#divAnswerSchemeContainer").html(data);}});

我的控制器中有一个添加答案操作:

[HttpPost]public PartialViewResult AddAnswer(AnswerScheme answerScheme){......这里有一些逻辑}

所以最后控制器收到模型,但只收到简单的属性,而不是列表.任何帮助将不胜感激!干杯.

解决方案

我希望我能看到更多你的类和代码,因为你没有正确设置.

我根据您提供的内容重新创建了一些内容,这很有效.我为此示例创建了一个 MVC 3 项目.

视图/共享/_Layout.cshtml

<头><title>@ViewBag.Title</title><link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"/><script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script><身体>@RenderBody()

视图/共享/_Partial.cshtml

@model RazorListTest.Models.AnswerScheme<表格>@for (int i = 0; i < Model.Answers.Count; i++) {<tr><td>@Html.HiddenFor(model => Model.Answers[i].IsMissing)@Html.TextBoxFor(model => Model.Answers[i].Value, new { @class = "inputValue" })</td><td>@Html.TextBoxFor(model => Model.Answers[i].Text, new { @class = "inputAnswer" })</td><td><span class="span-delete" data-answer-scheme-id="@Model.Id" data-answer-id="@Model.Answers[i].Id" >x</跨度></td></tr>}

模型/AnswerDisplayItem.cs

using System.Collections.Generic;命名空间 RazorListTest.Models{公共类 AnswerDisplayItem{public bool IsMissing { get;放;}公共字符串文本 { 获取;放;}公共字符串值 { 获取;放;}公共字符串 ID { 获取;放;}}公开课 AnswerScheme{公共列表答案 { 得到;放;}公共字符串 ID { 获取;放;}公共答案方案(){Answers = new List();}}}

主页/Index.cshtml

@model RazorListTest.Models.AnswerScheme@using (Html.BeginForm(null, null, FormMethod.Get, new { name="formAnswerScheme", id = "formAnswerScheme"})){{Html.RenderPartial("_Partial");}<div><input type="button" value="点击我" id="btnClick"/>

<div id="divAnswerSchemeContainer">

}<script type="text/javascript">$("#btnClick").click(function () {$.ajax({url: '主页/AddAnswer',类型:'POST',数据类型:'json',数据:$("#formAnswerScheme").serialize(),成功:功能(数据){控制台日志(数据);$("#divAnswerSchemeContainer").html(data);},错误:函数(xhr,textStatus,exceptionThrown){警报(JSON.parse(xhr.responseText));}});});

控制器/HomeController.cs

using System.Collections.Generic;使用 System.Web.Mvc;使用 RazorListTest.Models;命名空间 RazorListTest.Controllers{公共类 HomeController : 控制器{公共 ActionResult 索引(){AnswerScheme a = new AnswerScheme();a.Id = "1cd14b08-ce3b-4671-8cf8-1bcf69f12b2d";列表<AnswerDisplayItem>adi = new List();AnswerDisplayItem a1 = new AnswerDisplayItem();a1.IsMissing = false;a1.Text = "Ja";a1.Value = "0";a1.Id = "1234";AnswerDisplayItem a2 = new AnswerDisplayItem();a2.IsMissing = false;a2.Text = "Nein";a2.Value = "1";a2.Id = "5678";adi.Add(a1);adi.Add(a2);a.Answers = adi;返回视图(a);}[HttpPost]公共 JsonResult AddAnswer(AnswerScheme answerScheme){return Json("列表在模型中.");}}}

I have a simple form with a list of items in it and I'd like to post them to the controller but funny thing is I just cant. Everything else goes through properly except the list. I checked the ajax call in firebug and the post values are there like this:

Answers[0].IsMissing    False
Answers[0].Text Ja
Answers[0].Value    0
Answers[1].IsMissing    False
Answers[1].Text Nein
Answers[1].Value    1
Id  1cd14b08-ce3b-4671-8cf8-1bcf69f12b2d
Name    Ja/Nein

I have an AnwserScheme class with the following properties:

public string Name { get; set; }
public bool IsMissing { get; set; }
public List<AnswerDisplayItem> Answers { get; set; }

public AnswerScheme()
{
    Answers = new List<AnswerDisplayItem>();
}

I have this view code:

@for (int i = 0; i < Model.Answers.Count; i++) {
    <tr>
        <td>
            @Html.HiddenFor(model => Model.Answers[i].IsMissing)
            @Html.TextBoxFor(model => Model.Answers[i].Value, 
                             new { @class = "inputValue" })
        </td>
        <td>
            @Html.TextBoxFor(model => Model.Answers[i].Text, 
                             new { @class = "inputAnswer" })
        </td>
        <td>
            <span class="span-delete" 
                  data-answer-scheme-id="@Model.Id" 
                  data-answer-id="@Model.Answers[i].Id" >x</span>
        </td>
    </tr>
}

I have this piece of ajax code that is responsible for posting:

$.ajax({
    url: "/AnswerScheme/AddAnswer",
    type: "post",
    data: $("#formAnswerScheme").serialize(),
    success: function (data) {
                 console.log(data);
                 $("#divAnswerSchemeContainer").html(data);
             }
});

I have an add answer action in my controller:

[HttpPost]
public PartialViewResult AddAnswer(AnswerScheme answerScheme)
{
    ...some logic comes here
}

So in the end the controller recieves the model, but only the simple properties, not the list. Any help would be greatly appreciated! cheers.

解决方案

I wish I could see more of your classes and code, because you don't have something set up right.

I recreated something from what you did provide, which works. I created an MVC 3 project for this sample.

Views/Shared/_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>

    <body>
        @RenderBody()
    </body>
</html>

Views/Shared/_Partial.cshtml

@model RazorListTest.Models.AnswerScheme 

<table>
@for (int i = 0; i < Model.Answers.Count; i++) {
    <tr>
        <td>
            @Html.HiddenFor(model => Model.Answers[i].IsMissing)
            @Html.TextBoxFor(model => Model.Answers[i].Value, new { @class = "inputValue" })
        </td>
        <td>
            @Html.TextBoxFor(model => Model.Answers[i].Text, new { @class = "inputAnswer" })
        </td>
        <td><span class="span-delete" data-answer-scheme-id="@Model.Id" data-answer-id="@Model.Answers[i].Id" >x</span></td>
    </tr>
}
</table>

Models/AnswerDisplayItem.cs

using System.Collections.Generic;

namespace RazorListTest.Models
{
    public class AnswerDisplayItem
    {
        public bool IsMissing { get; set; }
        public string Text { get; set; }
        public string Value { get; set; }
        public string Id { get; set; }
    }

    public class AnswerScheme
    {
        public List<AnswerDisplayItem> Answers { get; set; }
        public string Id { get; set; }

        public AnswerScheme()
        {
            Answers = new List<AnswerDisplayItem>();
        }
    }
}

Home/Index.cshtml

@model RazorListTest.Models.AnswerScheme

    @using (Html.BeginForm(null, null, FormMethod.Get, new { name="formAnswerScheme", id = "formAnswerScheme"}))
    {
        {Html.RenderPartial("_Partial");}

        <div>
            <input type="button" value="Click me" id="btnClick"/>
        </div>

        <div id="divAnswerSchemeContainer">

        </div>
    }

<script type="text/javascript">
    $("#btnClick").click(function () {

        $.ajax({
            url: 'Home/AddAnswer',
            type: 'POST',
            dataType: 'json',
            data: $("#formAnswerScheme").serialize(),
            success: function (data) {
                console.log(data);
                $("#divAnswerSchemeContainer").html(data);
            },
            error: function (xhr, textStatus, exceptionThrown) { alert(JSON.parse(xhr.responseText)); }
        });
    });
</script>

Controllers/HomeController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using RazorListTest.Models;

namespace RazorListTest.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            AnswerScheme a = new AnswerScheme();

            a.Id = "1cd14b08-ce3b-4671-8cf8-1bcf69f12b2d";

            List<AnswerDisplayItem> adi = new List<AnswerDisplayItem>();
            AnswerDisplayItem a1 = new AnswerDisplayItem();
            a1.IsMissing = false;
            a1.Text = "Ja";
            a1.Value = "0";
            a1.Id = "1234";
            AnswerDisplayItem a2 = new AnswerDisplayItem();
            a2.IsMissing = false;
            a2.Text = "Nein";
            a2.Value = "1";
            a2.Id = "5678";
            adi.Add(a1);
            adi.Add(a2);
            a.Answers = adi;
            return View(a);
        }

        [HttpPost]
        public JsonResult AddAnswer(AnswerScheme answerScheme)
        {
            return Json("the list is in the Model.");
        }
    }
}

这篇关于如何在 MVC 中发布项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆