从一个动作向另一个动作发送价值

时间:2019-06-02 17:03:45

标签: asp.net-core

如何将参数从第一种方法传递给第二种方法? 我想在id中使用public async Task<IActionResult> CreateReport

public IActionResult CreateReport(int id)
{       
  return View();
}

// POST: MemeReports/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateReport([Bind("Id_report,Id_user,Id_meme,Description")] MemeReports memeReports)
{
  memeReports.id_meme=id //i want do this
  if (ModelState.IsValid)
  {
     db.Add(memeReports);
     await db.SaveChangesAsync();
     return RedirectToAction(nameof(Index));
  }
  return View(memeReports);
}

2 个答案:

答案 0 :(得分:0)

只需在您的post方法中传递它即可:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CreateReport(int id, [Bind("Id_report,Id_user,Id_meme,Description")] MemeReports memeReports)
    {
        memeReports.id_meme=id //i want do this
        if (ModelState.IsValid)
        {
            db.Add(memeReports);
            await db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(memeReports);
    }

如果调用站点yourdomain / createreport / 1(或yourdomain / createreport?id = 1)并显示createReport视图,则会调用您的第一个方法。

如果您从该页面提交帖子,您也将发布ID。

答案 1 :(得分:0)

您可以使用TempData来存储数据,直到被读取为止:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#tempdata

ConfigureServices函数中:

services.Configure<CookieTempDataProviderOptions>(options =>
{
    options.Cookie.IsEssential = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddSessionStateTempDataProvider();

services.AddSession();

Configure函数中:

app.UseCookiePolicy();
app.UseSession();

然后在CreateReport函数中:

public IActionResult CreateReport(int id)
{
    TempData["id"] = 1;

    return View();
}

您可以在post函数中读取该值:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateReport([Bind("Id_report,Id_user,Id_meme,Description")] MemeReports memeReports)
{
    var value = TempData != null ? (TempData["id"]?.ToString() ?? "No TempData Value") : "No TempData";
    memeReports.id_meme= value;
    if (ModelState.IsValid)
    {
        db.Add(memeReports);
        await db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(memeReports);
}

在用户接受网站上的cookie策略后,TempData应该可以工作。