2014-04-23 84 views
0

我試圖通過使用return view (ActionName, Model)將模型傳遞給動作。我已經知道TempData但我的問題是,當我在剃刀幾個文本框爲模型,例如像:ASP.NET MVC:返回視圖(ActionName,Model)

@Html.TextBoxFor (x=> x.Field1) 
And 
@Html.TextBoxFor (x=> x.Field2) 

當我與RedirectToAction一起使用TempData,在模型中的數據被加載到我的領域非常好,但是當我使用return View ("ActionName", MyModel)時,它會拋出Value cannot be null exception

如何我做的是這樣:

public ActionResult Act1() { 
    Model M = new Model() {Field1="123", Field2="245"}; 
    return View("Act2", M); 
} 

這引發異常,而這種方法的工作原理:

public ActionResult Act1() { 
    Model M = new Model() {Field1="123", Field2="245"}; 
    TempData["Model"] = M; 
    return RedirectToAction ("Act2"); 
    // then casting the TempData in the Act2 back to M and it works! 
} 

我的問題是,爲什麼ACT1方法導致錯誤? (剃刀部分是完全一樣的,問這個問題出於好奇)

編輯:

// Without TempData 

public ActionResult Act2 (Model model) { 
    return View(model); 
} 
+0

請問您可以展示第二個Action代碼'Act2'嗎? –

+0

@lnanikian:編輯了這個問題。 – JAX

+0

您是否期待'返回View(「Act2」,M);'調用'Act2'動作?如果這就是你想要做的,那麼這樣做:'返回Act2(M);' –

回答

0

看你的代碼,現在你需要添加回報View()

public ActionResult Act1() { 
    Model M = new Model() {Field1="123", Field2="245"}; 
    return View("Act2", M); 
} 
+0

對不起布盧姆,這是一個打字錯誤,我修正了 – JAX

+0

@PierreOverFlow你能不能在視圖中顯示一些代碼?像它爲模型接受什麼?無論如何,你是否遍歷它? –

+0

不,它只是一個非常簡單的模型,兩個字符串字段,我只是好奇它爲什麼不工作,而tempdata運行良好,模型有兩個字符串類型的屬性,所以在剃刀的兩個TextBoxes加載模型就這樣。 – JAX

0

在您的查看Act2if子句圍繞您的TempData[Model],然後檢查它是否爲空使用它否則不使用它。我認爲這是問題所在。這就是爲什麼當你嘗試使用它時它會在你嘗試它時拋出一個異常,但它是空的。

if (TempData[Model]!=null) 
    { 

    //Attempt it here and cast it here 
    } 
else 
    { 
    //Use your model 
    } 
+0

tempData已經起作用了,我想現在爲什麼使用return View(「Act2」,M)傳遞給動作的模型爲null。 – JAX

+0

你可以顯示視圖嗎?我不認爲'模型'爲空 –

+0

不,它說,傳遞的模型包含兩個空字段 – JAX