ModelView数据未从View传递到Controller

本文关键字:Controller View 数据 ModelView | 更新日期: 2023-09-27 17:53:23

我的问题是从我的控制器传递到我的视图的强类型数据是空的(它的所有属性都是空的(。

我还想将单选按钮中的选定值(标记为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"的参数转换失败,因为没有类型转换器可以在这些类型之间转换。">

ModelView数据未从View传递到Controller

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

这一行设置了一个复杂类型"@answer"作为单选按钮的值。这可能只是在渲染期间执行类型的ToString((。

当你把它发布回来时,MVC可能试图把这个字符串值转换回

Quiz.Models.Anwser

以及失败。

你可能应该呈现

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

另外,为什么不使用Html Extension来呈现单选按钮呢。

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

此外,对于答案,不要使用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和所选答案?