2016-11-18 21 views
-1

我想通過我的視圖將對象Guy傳遞給我的控制器,我不知道該怎麼做。 我試圖做一個@Model Guy在我看來,但沒有工作,所以我不知道如何將一個對象傳遞給我的Create方法,而不僅僅是一些變量,因爲我不想構建這個對象在方法中。 從我的研究中瞭解到,我必須使用defauldModelBinder來將我的模型綁定到視圖上,但是我不太清楚如何做到這一點,因爲我是一個完全新手。 任何提示?如果我的問題太基本,我很抱歉。如何使用defaultModelBinder將我的視圖綁定到我的模型?

我認爲目前看起來是這樣的:

@using (Html.BeginForm("Create", "Guys", FormMethod.Post)) 
{ 
    <input type="text" name="id" value="" /> 
    <input type="text" name="title" value="" /> 
    <input type="text" name="content" value="" /> 
    <input type="submit" /> 
} 

而且我的控制器是這樣的:

static List<Guy> Guys = new List<Guy> { new Guy(1,"phd","hi1"), new Guy(2, "proff", "hi2!"), new Guy(3, "proff.asst.", "hi3") }; 


public ActionResult Create(Guy obj) 
     { 

      Guys.Add(obj); 
      return RedirectToAction("Index", "Guys"); 
     } 

而且我的模型:

public class Guy 
{ 
    public int GuyId { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 


    public Guy(int GuyId, string Title, string Content) 
    { 
     this.GuyId = GuyId; 
     this.Title = Title; 
     this.Content = Content; 
    } 
} 
+0

嘗試在文本字段名稱中使用相同的模型名稱,嘗試在文本字段名稱中匹配案例,它應該可以工作 –

+0

即使我沒有@Model Guy?因爲由於某些原因我無法添加。 –

+0

如果您強烈地使用@model Guy(在您的視圖的頂部)鍵入您的視圖,則可以使用HTML助手。你正在使用的方法應該也可以,但是最好有一個強類型的視圖,並使用HTML助手進行模型綁定 –

回答

0

這可能是值得來定義默認模型中的構造函數,否則可能會出錯。除此之外,你的代碼似乎工作。

這是與我曾嘗試代碼:

public class HomeController : Controller 
{ 
    // GET: Home 
    [HttpGet] 
    public ActionResult Index() 
    { 
     return View(Guys.First()); 
    } 


static List<Guy> Guys = new List<Guy> { new Guy(1, "phd", "hi1"), new Guy(2,  "proff", "hi2!"), new Guy(3, "proff.asst.", "hi3") }; 

[HttpPost] 
public ActionResult Create(Guy obj) 
{ 

    Guys.Add(obj); 
    return RedirectToAction("Index", "Guys"); 
}} 

類蓋伊:

public class Guy 
{ 
    public int GuyId { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 

    public Guy() 
    { 

    } 

    public Guy(int GuyId, string Title, string Content) 
    { 
     this.GuyId = GuyId; 
     this.Title = Title; 
     this.Content = Content; 
    } 
} 

和查看:

@model Models.Guy 
 

 

 
@using (Html.BeginForm("Create", "Home", FormMethod.Post)) 
 
{ 
 
    <input type="text" name="GuyId" value="" /> 
 
    <input type="text" name="title" value="" /> 
 
    <input type="text" name="content" value="" /> 
 
    <input type="submit" /> 
 
}

相關問題