使用viewbag将id参数传递给控制器​​内部创建操作

时间:2016-05-17 08:33:09

标签: c# asp.net-mvc

在我的模型中,我在Users和Topics类之间有一对多的关系。这两个类的代码是

public class Topic
{
    public int TopicID { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; } 
    [Display(Name="Topic Subject")]
    public string TopicSubject { get; set; }
    [Display(Name="Date")]
    [DataType(DataType.Date)]
    public DateTime TopicDate { get; set; }
    [DisplayName("Name")]
    public int CatagoryID { get; set; }
    [DisplayName("FullName")]

    public virtual Catagory Catagories { get; set; }

    public virtual ICollection<Reply> Replies { get; set; }
}

public class User
{
    public int UserID { get; set; }

    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Display(Name="Password")]
    [DataType(DataType.Password)]
    public string UserPass { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }
    [Display(Name = "Full Name")]
    public string FullName
    {
        get { return FirstName + ", " + LastName; }
    }
    public virtual ICollection<Topic> Topics { get; set; }
    public virtual ICollection<Reply> Replies { get; set; }

}

在我的控制器中,action方法使用int id参数从视图内部传递id

public ActionResult Create(int id)
{
    ViewBag.CatagoryID = id;
    ViewBag.UserID = id;
    return View();
}

但是当我尝试在浏览器中访问“主题/创建”时,会出现这样的错误,这会让我烦恼:

enter image description here

3 个答案:

答案 0 :(得分:0)

您的Create方法是HttpGet版本 - 这意味着,为什么要为未创建的对象传递id以便创建&#34;创建&#34;一个东西?对于创建来说,这应该是空的,并且HttpPost应该传回模型,这样才能创建它。

尝试查看create mvc示例:http://www.asp.net/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part6

答案 1 :(得分:0)

要使控制器正常工作,您需要在查询参数中传递id。所以你需要使用以下网址。

http://localhost:63952/Topics/Create?id=1

如果您希望ID是可选的,则需要更改下面的操作方法。

public ActionResult Create(int? id)
{
    ViewBag.CatagoryID = id;
    ViewBag.UserID = id;
    return View();
}

以上将告诉C#id param是可选的,MVC不会指望它出现在查询参数上

希望这会有所帮助!!

答案 2 :(得分:-1)

尝试localhost:63952 / Create / 5 5表示您在创建函数中传递的ID 您可以尝试任何可以使用的数字