繁体   English   中英

未从View传递到Controller的ModelView数据

[英]ModelView data not passed from View to Controller

我的问题是从控制器传递到我的视图的强类型数据出来为空(所有属性均为null)。

我还想将单选按钮(标记为QUESTION2)中的选定值绑定到模型属性“ GivenAnwser”,但它似乎也不起作用。

传递的类型是ViewModel

public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {  
            QuestionViewModel question = Manager.GetQuestion();
            return View(question);
        }

        [HttpPost]
        public ActionResult Index(QuestionViewModel question,Anwser givenAnwser)
        {      
            //QuestionViewModel  is returned but all it's properties are null.           
            return View(question);
        }
    }

视图

@model Quiz.ViewModels.QuestionViewModel
@{
    ViewBag.Title = "Home Page";
}

@Html.Label("Question:")

@if (Model.CorrectAnwser != null)
{
    //some code
}

@Html.DisplayFor(model => model.Question.Text)

//I have tried with Hidden fields and without them
@Html.HiddenFor(model => model.Question)
@Html.HiddenFor(model => model.Anwsers)
@using (Html.BeginForm("Index", "Home"))
{         
    foreach (var anwser in Model.Anwsers)
    {
        //QUESTION 2
        <input type="radio" name="givenAnwser" value="@anwser" />
        <label>@anwser.Text</label>
        <br />
    }
    <input type="submit" value="Check!" />
}

QuestionViewModel

public class QuestionViewModel
    {
        public QuestionViewModel()
        {
            this.Anwsers = new List<Anwser>();
        }

        public Question Question { get; set; }

        public List<Anwser> Anwsers { get; set; }

        public Anwser GivenAnwser { get; set; }

        public bool CorrectAnwser { get; set; }

    }

编辑:ModelState包含错误:
“从类型'System.String'到类型'Quiz.Models.Anwser'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。”

 <input type="radio" name="givenAnwser" value="@anwser" />

此行将复杂类型“ @answer”设置为单选按钮的值。 这可能只是在渲染过程中执行的ToString()类型。

当您将其回发时,MVC可能正在尝试将此字符串值转换回

Quiz.Models.Anwser

和失败。

你应该渲染

<input type="radio" name="givenAnwser" value="@anwser.SomeBooleanValue" />

ps,为什么不使用Html Extension渲染单选按钮。

您不能将复杂类型(问题)绑定到“隐藏”字段。 您将需要绑定到单独的子属性。

另外,对于答案,请不要使用foreach,请使用for循环。 喜欢:

@for(var i=0;i<Answers.Count;i++)
{
    <input type="radio" name="@Html.NameFor(a=>a.Answers[i].answer.Value)" value="@Model.Answers[i].anwser.Value" />
}

要么

@for(var i=0;i<Answers.Count;i++)
{
    @Html.RadioButtonFor(a=>a.Answers[i].answer,Model.Answers[i].answer.Value)
}

虽然,这可能也不正确,因为Answers也是一个复杂类型的集合,并且您没有共享它的定义。

总而言之,我认为您真的不需要(也不想)将整个模型回发。 为什么不回发问题ID和选定的答案?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM