MVC 将数据从 View 发送到 Controller

MVC send data from View to Controller

我开始学习 asp.net MVC,这可能是个愚蠢的问题,但我似乎无法弄清楚我做错了什么。

我有一个 returns 数据的控制器,其中一些变量存储在 ViewBag 中。使用存储在 ViewBag 中的变量,我创建了一个 table(它们存储行数和列数)。

    [HttpGet]
    public ActionResult Index()
    {
        ViewBag.widht = someNumber1;
        ViewBag.height = someNumber2;
        return View(someData);
    }

   [HttpPost]
    public ActionResult Index(int someNuber)
    {
        //calculate the new width and height using someNumber
        ViewBag.widht = newWidth;
        ViewBag.height = newHeight;
        return PartialView();
    }

视图有一个按钮,当用户单击它时我想重新创建具有不同尺寸的 table。

    function OnClick_prev() {
    @Html.ActionLink("Index", "Index", new {id = ViewBag.width+5})
    }

我遇到的问题是 JavaScript 函数的主体抛出错误(在萤火虫中看到),不太确定为什么。错误是 SyntaxError: syntax error Index

有什么建议吗?

问题是 ViewBag 的基础类型是 ExpandoObjectExpandoObject 实际上是 Dictionary<string, object>,因此 ViewBag.width+5 等同于

object + int

无法编译。在执行计算之前,您需要将 width 属性 转换为 int

{ id = ((int)ViewBag.width + 5) }

像下面这样更改你的 JS

function OnClick_prev() {
    var loc = '@Url.Action("Index", "Index", new {id = (int)ViewBag.width+5})';
    window.location = loc;
}

编辑:刚刚意识到我最初的回答行不通,因为您使用的是 POST。

将您的 GET 方法更改为此

[HttpGet]
public ActionResult Index(int id)
{
    // Do some check on id to see if it has a value then add your old POST code here
    ViewBag.widht = someNumber1;
    ViewBag.height = someNumber2;
    return View(someData);
}

MVC 的默认路由为

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

因此您不必将 id 作为可选方法传递给该方法

然后在您看来将您的代码更改为

@Html.ActionLink("Index", "Index", new {id= (int)ViewBag.width+5})