POST请求在ASP中不起作用,什么也没发生

时间:2019-05-16 20:28:43

标签: c# asp.net-core asp.net-core-mvc

我的帖子请求不起作用。当我在编辑表单字段后尝试提交它时,表单字段会恢复为原始值,并且没有任何反应。预期的行为是,提交后,应用程序应重定向到其他页面并显示编辑后的值。

这是我的控制器中的代码:

[Route("Cheese/Edit/{id}")]
public IActionResult Edit(int id)
{
    Cheese cheeseToEdit = CheeseData.GetById(id);
    ViewBag.cheese = cheeseToEdit;
    return View();
}

[HttpPost]
[Route("/Cheese/Edit")]
public IActionResult Edit(int cheeseId, string name, string description)
{
    CheeseData.Edit(cheeseId, name, description);
    return Redirect("/Cheese");
}

这是来自表单的代码:

<h1>Edit Cheese</h1>

<form method="post">

    <div class="form-group">
        <label for="name">Name</label>
        <input class="form-control" name="name" id="name" type="text" value="@ViewBag.cheese.Name" />
    </div>
    <div class="form-group">
        <label for="description">Description</label>
        <input class="form-control" name="description" id="description" type="text" value="@ViewBag.cheese.Description" />
    </div>
    <div class="form-group">

        <input type="hidden" class="form-control" name="cheeseId" id="cheeseId" value="@ViewBag.cheese.CheeseId" />
    </div>

    <input type="submit" value="Add Cheese" />

</form>

这是CheeseData类中的代码,其中包含在Edit post方法中使用的Edit方法

public class CheeseData
{
    static private List<Cheese> cheeses = new List<Cheese>();

    //GetAll
    public static List<Cheese> GetAll()
    {
        return cheeses;
    }

    //Add
    public static void Add(Cheese newCheese)
    {
        cheeses.Add(newCheese);
    }

    //Remove
    public static void Remove(int id)
    {
        Cheese cheeseToRemove = GetById(id);
        cheeses.Remove(cheeseToRemove);
    }

    public static void Edit(int id, string name, string description)
    {
        int index = CheeseData.GetAll().FindIndex(m => m.CheeseId == id);
        cheeses[index].Name = name;
        cheeses[index].Description = description;
    }

    //GetById
    public static Cheese GetById(int id)
    {
        //this is linq method syntax.  the Single method returns the one object from the
        //list that matches the criteria
        return cheeses.Single(x => x.CheeseId == id);
    } 
}

0 个答案:

没有答案