2017-09-17 219 views
0

我的應用程序是MVC核心C#中,我從一個方法兩個項目,對象和字符串返回一個通用存儲庫:.NET核心System.ValueTuple

public object PostWebApi(TObject model, string url, string dir) 
     {... 
    return (model, msg);} 

在控制器我用

var data = _studentService.PostWebApi(WebApiDirectory()); 
return View(data) 

傳遞模型到視圖,我得到錯誤

The model item passed into the ViewDataDictionary is of type 'System.ValueTuple 

enter image description here

在調試時,返回的對象有兩個項目,模型和字符串。 無法弄清楚如何將模型item1傳遞給視圖。

+0

你的價值觀,你可以顯示您的視圖的代碼?它看起來像你的看法是期待不同的類型 – Jonesopolis

+0

@model WebUI.Models.Student。該方法返回我想用於ViewBag的模型和字符串。挑戰是如何分割item1和item2。 – hncl

+0

@GiladGreen你需要安裝c#7的新版本。 Install-Package System.ValueTuple -Version 4.4.0。它的工作,我的應用程序是核心2.0。 – hncl

回答

1

當您執行return View(data)時,您將值元組返回到您的視圖,其中data是值元組的結果。你需要返回data.Item1。

其中之一,你應該命名你的PostWebApi方法中的元組返回值爲了可讀性的目的。所以,而不是像public (Student, String) PostwebApi()之類的東西,你想要的東西像public (Student student, String msg) PostWebApi()

然後在你的控制器裏,你可以做return View(data.student);如果你需要元組的其他部分,你可以通過data.msg來訪問它。

+0

謝謝。我改變了回報: public Object PostWebApi(TObject model,string url,string dir){... var result = new {student = model,message = msg};它返回:data {student = {WebUI.Models.Student},message =「{\」id \「:23,\」lastName} 無法使用data.student,得到一個錯誤(沒有引用), – hncl

+0

因此,在返回View(data.student)之前調試;'''顯示學生有一個值,但在RazorView中ViewModel是空的? –

+0

我無法在控制器中使用data.student。錯誤是我返回的對象沒有爲學生提供參考;我認爲錯誤是由於返回一個對象? – hncl

2

另一種可能是你改變視圖模型

@model System.ValueTuple<WebUI.Models.Student, object> 

和訪問項目1項目2禮儀

+0

有趣的,會試試看。謝謝 – hncl