如何在asp.net mvc中的不同操作(GET,POST,DELETE)上执行不同的代码

时间:2014-04-09 05:46:09

标签: c# asp.net-mvc

这是我在家庭控制器中的索引方法。我在索引页面上有一个提交表单,我只希望代码在他们点击提交按钮时运行。我已经习惯了网络表格,所以如果你能提供一些建议,我会对这个问题有点困惑。

public ActionResult Index(EssayInfoModels c)
{
    if (ModelState.IsValid)
    {
        try
        {
            // attempting to load the dropdownlist with choices here but it fails when the page first loads because there is nothing in it yet.
            if (c.topicList.Count == 0)
            {
                c.topicList.Add(new SelectListItem { Text = "Math", Value = "Math" });
                c.topicList.Add(new SelectListItem { Text = "Science", Value = "Science" });
            }


            // send message code here
            return View("Success");
        }
        catch (Exception ex)
        {
            return View("Error");
        }
    }
    else
    {
        return View();
    }
}

3 个答案:

答案 0 :(得分:0)

使用[HttpGet][HttpPost]

[HttpGet]
public ActionResult Index()
{
   return View()
}

[HttpPost]
public ActionResult Index(EssayInfoModels c)
{
   // YOUR CODE
   return View()
}

答案 1 :(得分:0)

坦率地说,我有点震惊,你有这个问题。这是非常基本的,几乎在任何教程的第一步都会解释。但是,尽管如此......

您可以使用属性来创建Get和Post方法。

[HttpGet]
public ActionResult Index() {
   return View();
}

[HttpPost]
public ActionResult Index(EssayInfoModels c)
{
    // process your posted data...
}

答案 2 :(得分:0)

你可以使用另一个具有属性[HttpPost]的Index方法,如下所示

public ActionResult Index() --> Get Action of Index
{
   ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

   return View();
}

[HttpPost]
public string Index(FormCollection fc) --> Triggers when you click a button (POST action)
{
    return "In post Index";
}

要激活此功能,您必须在索引视图中有表格,如下所示

@using (Html.BeginForm())
{
    <input type="submit" value="click" />
}

因此,当您单击此按钮时,它将触发索引

的[HttpPost]操作