2017-01-04 81 views
1

我正在製作我的MVC應用程序。我打開我的觀點與預定義的參數是這樣的:在視圖中傳遞MVC數據

return RedirectToAction("PickGroupForHomework", "Account", new {subject_id = id, qty=model.qty }); 

而這個工作正常,數據subject_idqty正確傳遞。但是,我的視圖PickGroupForHomework包含一個要填充的表單,然後進行驗證。如果輸入無效,則窗口只需重新加載前面視圖中定義的數據subject_idqty。我這樣做是這樣的:

public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model) 
     { 
      ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2(); 
      model.groups = entities.Groups.ToList(); 
      model.users = entities.Users.ToList(); 
      int id = model.subject_id; 
      var subj = entities.Subjects 
        .Where(b => b.class_id == model.subject_id) 
        .FirstOrDefault(); 
      if (subj != null) 
      { 
       model.subject_name = subj.name; 
      } 
      if (ModelState.IsValid) 
      { 

      } 
      else 
      { 
       return View(model); 
      } 
      return View(model); 

     } 

但結果URL不包含我需要的數據,但只是一個普通的看法。我該如何做對?

+0

何不你不使用不顯眼的驗證。這意味着大多數問題都會被客戶端發現 – Liam

+0

你也可以顯示視圖嗎? – user7351608

+0

@KwekuReginaldWade查看編輯 – jjj21

回答

0

爲了讓您的WEP應用工作,你將需要兩個動作,一個設置模型彌補了查看和另一個實際做的工作後,保存您的數據:

public ActionResult PickGroupForHomework(int subject_id, int qty) 
    { 
     //Initialize your model here. Below is just an example. 
     ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2(); 

     PickGroupForHomeworkViewModel model = new PickGroupForHomeworkViewModel(); 

     model.groups = entities.Groups.ToList(); 
     model.users = entities.Users.ToList(); 

     model.subject_id = subject_id; 
     model.qty = qty; 

     return View("PickGroupForHomework", model); 
    } 

    [HttpPost] 
    public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model) 
    { 
     ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2(); 

     int id = model.subject_id; 

     var subj = entities.Subjects 
       .Where(b => b.class_id == model.subject_id) 
       .FirstOrDefault(); 

     if (subj != null) 
     { 
      model.subject_name = subj.name; 
     } 
     if (ModelState.IsValid) 
     { 
      //Save to database 
      [code goes here] 

      //return to a View to show your results 
      return View("[Your view to see the results]") 
     } 

     //Model Validation did not pass 
     //or exception occurred go back to View 
     return View(model); 
    } 
+1

這不能解決問題 – jjj21

+0

調試時代碼採用什麼路徑? – user7351608

+1

當我打開它從不同的窗口移動,它是'http:// localhost:3449/Account/PickGroupForHomework?subject_id = 2&qty = 4',但是,然後,錯誤的驗證後,它得到'http:// localhost:3449/Account/PickGroupForHomework' – jjj21