2016-04-01 149 views
0

我一直在創建一個ASP.NET MVC程序,會隨機選擇一個學生和隨機選擇一個問題,出於某種原因,我不能讓它在.cshtml文件中工作的麻煩。難道我做錯了什麼?此外,我得到這個錯誤ASP.Net MVC隨機,控制器和視圖

「傳遞到字典的模型產品類型‘QuizProgramMVC.Models.Student’,但這部詞典需要類型‘QuizProgramMVC.Models.StudentQuestion’的典範項目。」用` QuizProgramMVC.Models;

控制器

public class QuizController : Controller 
{ 
    public QuizController TheQuiz { get; set; } 

    // GET: Quiz 
    public ActionResult Index() 
    { 
     StudentQuestion sq = new StudentQuestion(); 

     return View(sq); 
    } 

    public ActionResult QuizProgram() 
    {   
     Student program = new Student(); 

     return View(program); 
    } 

} 

查看

@model QuizProgramMVC.Models.StudentQuestion 
@using QuizProgramMVC.Models; 

@{ 

    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>QuizProgram</title> 
</head> 
<body> 
    <div> 
     <h1>Quiz Program</h1> 

       <div class="row"> 
        <div class="col-md-6"> 
         <table class="table table-condensed"> 
          <thead> 
           <tr> 
            <th>Question</th> 
            <th>Answer</th> 
           </tr> 
          </thead> 
          <tbody> 
           @foreach (Question q in Model.Questions) 
           { 
            <tr> 
             <td> 
              @q.Quest 
             </td> 
             <td> 
              @q.Answer 
             </td> 
            </tr> 
           } 
          </tbody> 
         </table> 
        </div> 
       </div> 
      <br/> 
       <div class="row"> 
        <div class="col-md-6"> 
         <table class="table table-condensed"> 
          <thead> 
           <tr> 
            <th>First Name</th> 
            <th>Last Name</th> 
           </tr> 
          </thead> 
          <tbody> 
           @foreach (Student s in Model.Students) 
           { 
            <tr> 
             <td> 
              @s.FirstName 
             </td> 
             <td> 
              @s.LastName 
             </td> 
            </tr> 
           } 
          </tbody> 
         </table> 
        </div> 
       </div> 
     <br/> 
     @using (Html.BeginForm()) 
     { 
      <div> 
       Type Answer: <input id="param1" name="param1" type="text" /> 
       <br /> 
       <input type="submit" value="Submit" /> 
      </div> 
     } 
    </div> 
</body> 
</html> 
+2

錯誤信息不明顯嗎?您的行爲方法所傳遞的類型與預期不同。而不是Student對象,您需要傳遞'StudentQuestion'對象,因爲您的視圖是強類型的。 – Shyju

回答

0

問題是你在呼喚與不同型號相同的觀點頁。

public ActionResult QuizProgram() 
{   
    Student program = new Student();//Here you need to pass the StudentQuestion to the view. 
    return View(program); 
} 

通過QuizProgram()拋出一個錯誤,因爲在該視圖頁面所定義的模型

@model QuizProgramMVC.Models.StudentQuestion 

,不允許其他的ViewModels,因爲它調用上面的查看頁面(.cshtml)是強類型查看。