如何在ASP.NET MVC项目中将id属性传递给控制器​​的动作?

时间:2013-03-14 18:41:16

标签: c# asp.net asp.net-mvc web-applications

我是asp.net的新手,如果有人可以帮助我,我会非常感激。 我认为我有一个表格:

@using (Html.BeginForm("Edit", "Projects", FormMethod.Post, new { enctype = "multipart/form-data", id = serviceId })) 
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Project</legend>

            @Html.LabelFor(model => model.Title)     
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)       

            @Html.LabelFor(model => model.Description)

            @Html.TextAreaFor(model => model.Description, new { rows = 20})
            @Html.ValidationMessageFor(model => model.Description)

            <input type="submit" value="Save"  />

</fieldset>
}

serviceId我通过ViewData(在控制器中声明):

@{
    var serviceId = ViewData["serviceid"];
 }

现在提交时我想将此serviceId传递给我的ActionResult,在此视图中我添加了脚本:

  $(function () {
    $("form").submit(function () {

        $.post("Projects/Edit", {Sid: $(this).attr('id'), }, function (data) {

        });
    });
});

在我的Projects控制器中,在Edit ActionResult中我将此id作为参数:

[HttpPost]
    public ActionResult Edit(Models.Project EditedProject, int Sid)
    {
        Models.DBProjects dbproject = new Models.DBProjects();
        PoleInvestProjectContext context = new PoleInvestProjectContext();
        UserAccount curUser = context.Users.Where(u => u.UserName ==    User.Identity.Name).First();
        EditedProject.UserId = curUser.UserId;

        EditedProject.ServiceId = Sid;
        dbproject.EditProject(EditedProject);

        return RedirectToAction("Index", new { id = Sid });
    }

这是Error :(当我尝试提交表单时:

The parameters dictionary contains a null entry for parameter 'Sid' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(MyProject.Models.Project, Int32)' in 'MyProject.Controllers.ProjectsController'. 
An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

如果有人可以提供帮助,我会很感激! 提前谢谢!

1 个答案:

答案 0 :(得分:1)

使用视图模型,抛弃javascript和ViewData

public class EditViewModel()
{
  public string Title {get; set;}
  public string Description {get; set;}
  public int ServiceId {get; set;}
}

将ServiceId设置为viewModel属性而不是ViewData    控制器中的对象。

强烈地将视图输入到viewModel而不是实体    对象

然后使用隐藏字段将值传递回控制器

@Html.LabelFor(model => model.Title)     
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)       
@Html.LabelFor(model => model.Description)
@Html.TextAreaFor(model => model.Description, new { rows = 20})
@Html.ValidationMessageFor(model => model.Description)

@Html.HiddenFor(model => model.ServiceId)

<input type="submit" value="Save"  />

并更改你的帖子后签名

[HttpPost]
public ActionResult Edit(EditViewModel viewModel)
{
  //...