【问题标题】:How to use defaultModelBinder in order to bind my view to my model?如何使用 defaultModelBinder 将我的视图绑定到我的模型?
【发布时间】:2017-04-02 14:33:17
【问题描述】:

我试图通过我的视图将对象Guy 传递给我的控制器,但我不知道该怎么做。 我试图在我看来做一个@Model Guy,但这没有用,所以我不知道如何将对象传递给我的 Create 方法,而不仅仅是一些变量,因为我不想构建这个方法中的对象。 根据我从研究中了解到的情况,我必须使用 defauldModelBinder 才能将我的模型绑定到视图,但我不太清楚如何做到这一点,因为我是一个完全的新手。 有小费吗?如果我的问题太基本,我很抱歉。

我的观点目前是这样的:

@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 帮助器进行模型绑定
  • 我之前尝试过同样的事情,我得到 Guy 用红色下划线(在 @model Guy 中)​​和错误“找不到类型或命名空间名称“Guy””。

标签: c# asp.net-mvc


【解决方案1】:

在模型中定义一个默认构造函数可能是值得的,否则你可能会得到一个错误。除此之外,您的代码似乎可以工作。

这是我尝试过的代码:

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" />
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多