在ActionLink上通过Controller传递字符串

时间:2016-08-22 22:38:46

标签: asp.net-mvc razor

我想将序列号(或ESN)从当前页面传回新页面。我试图在我的第一页上调用此代码。

查看1

@Html.ActionLink("Details", "InventoryDetails", "ItemReconcilliation", new {ESN = mySerialNumber})

其中mySerialNumber是经验证具有良好数据的变量。

控制器

public ActionResult InventoryDetails(HistoryModel model, string ESN)
{
    model = new HistoryModel (ESN);
    return View(model);
}

但是,我的ESN变量总是返回null。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我不确定为什么你的方法中有HistoryModel参数,我认为你不需要它。只需在方法体中创建一个新的HistoryModel。

对于ActionLink,从内存中你需要在ActionLink的末尾添加一个额外的null参数,如下所示:

@Html.ActionLink("Details", "InventoryDetails", "ItemReconcilliation", new {ESN = mySerialNumber},null)

它应该正确呈现。

编辑: 您的初始方法应该是这样的:

public ActionResult InventoryDetails(string ESN)
{
   HistoryModel viewModel = new HistoryModel(ESN);
   return View(viewModel);
}

接下来是您将表单/模型实际提交给控制器的方法:

[HttpPost]
public ActionResult InventoryDetails(HistoryModel viewModel)
{
   //do work with viewModel, such as saving it to the database.

   return RedirectToAction("Index");
}

如果您想要将一个html类/属性添加到ActionLink,那么您将用{替换null。例如:

@Html.ActionLink("Details","InventoryDetails", "ItemReconcilliation", new { ESN = mySerialNumber }, new { @class = "snazzyCSSStyleClass" })
相关问题