首页 \ 问答 \ MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)

MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)

我很难从我的MVC4应用程序中发布到Controller的小型多选问卷中获取值:

该模型如下所示:

public class Evaluation
{
    public int Id { get; set; }    
    public IEnumerable<MultipleChoiceQuestion> Question { get; set; }    
    public Remark Rem { get; set; }
}

public class MultipleChoiceQuestion
{
    public int Id { get; set; }    
    public string Question { get; set; }    
    public MultipleChoiceAnswer Answer { get; set; }
}

public enum MultipleChoiceAnswer
{
    DISAGREE,
    NEUTRAL,
    AGREE,
    NA,
}

这是视图(省略一些标记):

@model Models.Evaluation

@using (Html.BeginForm("EvaluationB", "Evaluation", FormMethod.Post))
{
        @foreach (var item in Model.Question)
            {
                @Html.DisplayFor(model => item.Question)
                @Html.EditorFor(model => item.Question, "Enum_RadioButtonList", new { Id = item.Id })
            }
            @Html.Label("Remark")
            @Html.TextAreaFor(model => model.Rem)

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

“Enum_RadioButtonList”是一个从这里抓取的View: https ://gist.github.com/973482。 这似乎是在radiobuttonlist中显示枚举值的最佳方式(在MVC 4中它们应该是一种更简单的方式)

控制器看起来像这样:

    public ActionResult EvaluationA()
    {
        Models.Evaluation evm = new Models.Evaluation();
        evm.Question = db.MultipleChoiceQuestions.ToList(); //feeding the View some predefined questions
        return View(evm);
    }

    public ActionResult EvaluationB(Models.Evaluation ev)
    {
        if (ModelState.IsValid)
        {
            // TODO: save model
            return View("EvaluationB", evm);
        }

        return View("EvaluationA", ev);
    }

问题在View中正确加载,但出于某种原因,发布到Controller的模型在HttpPost之后仍然为空,我不明白为什么。


I'm having a hard time getting the values from a small multiple choice questionnaire posted to the Controller in my MVC4 app:

The model looks like this:

public class Evaluation
{
    public int Id { get; set; }    
    public IEnumerable<MultipleChoiceQuestion> Question { get; set; }    
    public Remark Rem { get; set; }
}

public class MultipleChoiceQuestion
{
    public int Id { get; set; }    
    public string Question { get; set; }    
    public MultipleChoiceAnswer Answer { get; set; }
}

public enum MultipleChoiceAnswer
{
    DISAGREE,
    NEUTRAL,
    AGREE,
    NA,
}

This is the View (leaving out some markup):

@model Models.Evaluation

@using (Html.BeginForm("EvaluationB", "Evaluation", FormMethod.Post))
{
        @foreach (var item in Model.Question)
            {
                @Html.DisplayFor(model => item.Question)
                @Html.EditorFor(model => item.Question, "Enum_RadioButtonList", new { Id = item.Id })
            }
            @Html.Label("Remark")
            @Html.TextAreaFor(model => model.Rem)

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

The "Enum_RadioButtonList" is a View a grabbed from here: https://gist.github.com/973482. It seems like the best way to show enum values in a radiobuttonlist (tho their should be an easier way in MVC 4)

The Controller looks like this:

    public ActionResult EvaluationA()
    {
        Models.Evaluation evm = new Models.Evaluation();
        evm.Question = db.MultipleChoiceQuestions.ToList(); //feeding the View some predefined questions
        return View(evm);
    }

    public ActionResult EvaluationB(Models.Evaluation ev)
    {
        if (ModelState.IsValid)
        {
            // TODO: save model
            return View("EvaluationB", evm);
        }

        return View("EvaluationA", ev);
    }

The questions are loaded fine in the View, but for some reason, the model posted to the Controller remains empty after an HttpPost, and i don't understand why.


原文:https://stackoverflow.com/questions/14051730
更新时间:2019-12-02 00:07

最满意答案

我没有看到表单有如下ID的映射:

@Html.HiddenFor(model => model.Id)

每个内部问题集合也应该具有Id,以便与表单一起发布。 因此,对于您可以拥有的每个问题,在表单的foreach循环中:

@Html.HiddenFor(model => item.Question.Id)

该模型还具有MultipleChoiceQuestion类型的集合。 对于模型绑定到集合,集合元素的名称应具有带有序数字的name属性,如本文http://haacked.com/archive/2008/10/23/model-binding-to-a-list中所述。 ASPX


Ive done some more research stumbled upon this post:

http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx

The problem was in the naming of the html fields. Ive added my View like this and now i can read out the values in the Controller correctly:

    @for (int i = 0; i < 6; i++)
    {
    <tr>
        <td>
            @Html.DisplayFor(m => m.Question[i].Question)
        </td>
        <td class="mult_question">
            @Html.EditorFor(m => m.Question[i].Answer, "Enum_RadioButtonList" )
        </td>
    </tr>
    }

<tr>
    <td>
        @Html.Label("Remark")
        @Html.TextAreaFor(m => m.Remark)
2012-12-27

相关问答

更多

如果没有注释,Rust无法推断类型(Rust cannot infer type without annotation)

问题是MyHashGenerator没有采用类型参数。 所以你做了一个承诺“ 相同的类型MyHashGenerator就足以作为一个哈希生成器,并且无论T如何都会以完全相同的方式运行”。 self.hash("")是对HashGenerator hash调用,但Rust并不一定知道它与 HashGenerator实例相同 。 您可以通过以下两种方式之一明确说明此要求。 选项1:显式类型参数 通过明确告诉Rust参数是什么,可以避免这个问题。 fn hash_node(&self) -> u64

数学计算 - 浮点数[重复](Math Calculation - float numbers [duplicate])

你应该这样做 float years = (1.0/31536000.0) * 883102.00; 要么 float years = (1.0/31536000) * 883102.00; 可能也会有效。 您的第一个数字被视为整数。 You should instead do float years = (1.0/31536000.0) * 883102.00; or float years = (1.0/31536000) * 883102.00; might work as wel

添加资源和设置Exe描述[重复](Adding resources and setting Exe description [duplicate])

看看我的朋友。 我认为这会让你感到厌烦,因为这个人有同样的问题: 我们如何将嵌入式资源添加到在运行时从源文件编译的文件中 Have a look here my friend. I think this will sort you out as the guy was having the very same issue: How can we add embedded resources to a file which is compiled from a source file at run

改进MS Project VB / VBA任务创建(improving MS Project VB/VBA task creation)

额外任务的问题可以通过存储所选任务的集合(或.net中的列表)然后循环遍历这些任务来解决。 我在VBA中发布解决方案,因为这可能与其他观众最相关; 如果需要,我可以发布一个vb.net版本。 Application.ScreenUpdating = False Dim proj As Project Set proj = Application.ActiveProject Dim myTask As Task Dim colTasks As New Collection For Each m

用KafkaConsumer 0.10.0读取0.9.0消息?(Read 0.9.0 messages with KafkaConsumer 0.10.0?)

前段时间我在Kafka Jira开了一个类似的问题,得到了一个非常明确的答案 - 首先是升级经纪人,然后是客户,而不是反过来。 这确保了实现处理您的请求所需的所有功能,并且代理可以优雅地处理它。 如果您对详细信息感兴趣,请点击此处打开的问题链接 - https://issues.apache.org/jira/browse/KAFKA-2496 。 Some time ago I've opened a similar issue in Kafka Jira and got a quite un

使用live时,unbind click不起作用(unbind click doesn't work when using live)

与.live()相反的是.die() : http : .die() $("#test").die('click').click(function(){ //unbind alert("test2"); }); BTW: .live()自1.7以来被弃用。 但是如果你使用旧版本的jQuery,我发现使用它没有问题。 The opposite of .live() is .die(): http://api.jquery.com/die/ $("#test").die('click').cl

scala:施工顺序和早期定义(继承)(scala: construction order and early definitions (inheritance))

在你的评论之后,我决定真正看看书中究竟写了什么。 在阅读了解释之后,我决定不能更清楚地表达它。 所以相反,我建议看看完全脱落的代码,因为短篇小说中没有地方。 将其另存为Scala脚本: class Animal { val range: Int = 10 val env: Array[Int] = new Array[Int](range) } class Ant extends Animal { override val range: Int = 2 } val ant = n

在[关闭]列中找到一些值(Find some value in column [closed])

你需要在列panel_mm_id上merge panel_mm_id ,使用inner join ( how='inner' ),可以省略什么,因为默认情况下: df2.columns = ['panel_mm_id'] df = (pd.merge(df1, df2, on='panel_mm_id')) print (df) 样本(1. panel_mm_id列中df1的panel_mm_id已更改): import pandas as pd df1 = pd.DataFrame({'

相关文章

更多

最新问答

更多
  • 根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)
  • 分开foreach项目并单独打印(Separate foreach items and print them individually)
  • 写模式管道是否同步?(Is write mode pipe synchronous?)
  • 发现可用的Windows Phone强调色和本地化名称(Discover available Windows Phone accent colors and localized names)
  • 使用多线程和WPF更新集合(Update Collection with multithreading and WPF)
  • 如何在字符串的情况下使用同步?(How should the synchronization be used in case of strings?)
  • 打印唯一的行,比较不超过N个字符(Print unique lines, compare no more than N characters)
  • Javascript / jQuery - 如何调用switch case从另一个函数执行(Javascript/jQuery - how to call a switch case to execute from another function)
  • Hbase超时错误不断发生(Hbase timeout errors keep occuring)
  • 如何在Delphi中更改TabControl中活动TAB的颜色(How to change the color of active TAB in a TabControl, in Delphi)
  • 正则表达式:在sublime文本中替换一些PHP代码(Regex: replace some pieces of php code in sublime text)
  • 在带有Scene2D的LibGDX中,如何在按下按钮时连续向右走?(In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?)
  • 累加器如何在Haskell中工作?(How do accumulators work in Haskell?)
  • 使用开关检查市场和前缀与正确的货币符号(using switch to check market and prefix with correct currency symbol)
  • 在哪里分配一次使用类?(Where to allocate one time use class?)
  • 如何从两个DateTime / NaiveDateTime获取持续时间?(How do I get Duration from two DateTime / NaiveDateTime?)
  • 解析TimeSpan大于24小时?(Parse a TimeSpan greater than 24 hours? [duplicate])
  • 如何在球拍中本地更改阅读规则?(How to locally change reading rules in racket?)
  • 数据库应该由DI注入时的模拟存储(通过构造函数)(Mock storage when database should be injected by DI (through constructor))
  • 使用maven集成2个eclipse项目(Integrate 2 eclipse projects using maven)
  • 角度ng-repeat不检测变化(Angular ng-repeat not detecting changes)
  • Xaml组件在Silverlight + XNA应用程序的多个页面中可见(Xaml component visible in multiple pages in Silverlight+XNA applications)
  • 如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)
  • 如何设计hyperledger链代码以适合您的业务?(how to design your chaincode of hyperledger to fit for your business?)
  • PHP readfile错误(PHP readfile error)
  • 在Date之后排序列表然后是时间(Sorting list after Date then time)
  • Android内部版本号(Android build number)
  • 在没有预设退出条件的情况下停止无限循环(stopping an infinite loop with no preset exit condition)
  • Phonegap应用程序全屏通过html页面中的按钮(Phonegap Application fullscreen through a button in html page)
  • PAA是否适合在门户网站中自动执行wcm库部署和设置?(Is PAA a good candidate for automating wcm library deployment and setup in portal?)