MVC3 操作链接将 ID 附加到对象



我有一个带有数据的对象视图,该视图上有一个按钮。用户可以查看对象信息并单击按钮转到新的视图表单,他可以输入信息来创建项目。我的挑战是,我将如何在上一个视图上附加对象的 ID 以将其与他们创建和提交的信息相关联并附加到这些信息?

@Html.ActionLink("Add","AddNotes","Object",new {@id=5},null)

这将创建一个带有查询字符串?id=5 的标记。(您可以将硬编码的 5 替换为视图中的动态值)

具有一个属性,用于为创建窗体的ViewModel/Model保留此值。

public class CreateNoteViewModel
{
  public int ParentId { set;get;}
  public string Note { set;get;}
  //Other properties also
}

在 GET action 方法中阅读此内容,该方法将创建第二个视图并设置视图模型/模型的属性的值。

public ActionResult AddNotes(int id)
{
  var model=new CreateNoteViewModel();
  model.ParentId=id;
  return View(model);
}

在强类型视图中,将此值保留在隐藏变量中。

@model CreateNoteViewModel
@using(Html.BeginForm())
{
 @Html.TextBoxFor(Model.Note)
 @Html.HiddenFor(Model.ParentId)
 <input type="submit" />
}

现在,在HttpPost操作中,您可以从 POSTED 模型的 ParentId 属性中获取对象 ID

[HttpPost]
public ActionResult AddNotes(CreateNoteViewModel model)
{
 if(ModelState.IsValid()
 {
   //check for model.ParentId here
   // Save and redirect
 }
 return View(model); 
}

你可以使用隐藏的输入和视图数据,伪代码。 注意 您可能必须将字符串与视图数据一起使用,并在控制器中转换回您的 ID。 有关ViewData/ViewBag(和缺点)的基本解释,请参阅此链接。

您需要将数据从第一个操作(控制器)传递到视图控制器基类具有"ViewData"字典属性,可用于填充要传递给视图的数据。 您可以使用键/值模式将对象添加到 ViewData 字典中。

控制器

 public ActionResult yourfirstaction()
      {
            //assign and pass the key/value to the view using viewdata
            ViewData["somethingid"] = ActualPropertyId;

在视图中 - 获取值 将其与隐藏的输入一起使用,以传递回下一个控制器以呈现下一个视图

 <input type="hidden" name="somethingid" value='@ViewData["somethingid"]' id="somethingid" />

控制器

  public ActionResult yournextaction(string somethingid)
      {
            //use the id
            int ActualPropertyId =  Convert.ToInt32(somethingid);

最新更新