-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;
}
}
嘗試在文本字段名稱中使用相同的模型名稱,嘗試在文本字段名稱中匹配案例,它應該可以工作 –
即使我沒有@Model Guy?因爲由於某些原因我無法添加。 –
如果您強烈地使用@model Guy(在您的視圖的頂部)鍵入您的視圖,則可以使用HTML助手。你正在使用的方法應該也可以,但是最好有一個強類型的視圖,並使用HTML助手進行模型綁定 –