0

我是 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控制器中,在EditActionResult 中,我将此 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.

如果有人可以提供帮助,我将不胜感激!提前致谢!

4

1 回答 1

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)
{
  //...
于 2013-03-14T18:49:25.587 回答