MVC 表单加载调用控制器方法及其重载方法而不是调用单击方法?附上代码

问题描述 投票:0回答:1

我正在单击按钮保存数据,但在第一次加载进入重载方法时查看?

我的视图代码就像,

@using (Html.BeginForm("ManageQuestion", "Questions", FormMethod.Post))
{
 <input type="submit" value="Save" /> 
}

我的控制器就像,

public ActionResult ManageQuestion()
{
    //List<SelectListItem> QuestionType = Survey();
        //return View(QuestionType);
        return View();
}

[HttpPost]
public ActionResult ManageQuestion(Question Objquest)
{

    if (ModelState.IsValid)
    {
        SurveyAppEntities ObjEntity = new SurveyAppEntities();
        string strDDLValue = Request.Form["DDlDemo"].ToString();
        Objquest.QuestionType = strDDLValue;
        ObjEntity.Questions.Add(Objquest);
        ObjEntity.SaveChanges();
        ViewData["error"] = "Question Saved successfully";
        if (Objquest.ID > 0)
        {
        //    ViewBag.Success = "Inserted";

        }
        ModelState.Clear();
    }

    return View();
}

}

我认为它必须在单击按钮时调用重载 ManageQuestion 方法,但是当第一次加载视图时,它会进入重载方法,从而导致错误。

我从网上得到了一个具有相同场景的示例,但重载方法在第一个表单加载时没有调用?

希望您的建议

谢谢

c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 model-view-controller
1个回答
0
投票

您似乎想避免在首次加载视图时执行 [HttpPost] 方法。实现此目的的一种常见方法是检查请求是否是 POST 请求。您可以修改 [HttpPost] 方法,使其仅在 POST 请求时执行逻辑。这是一个例子:

  public ActionResult ManageQuestion()
{
    // This method will be called when the view is first loaded
    // Add any necessary logic here
    return View();
}

[HttpPost]
public ActionResult ManageQuestion(Question Objquest)
{
    // This method will be called when the form is submitted (POST request)
    if (ModelState.IsValid)
    {
        // Your logic for saving the data
    }

    // Regardless of whether the data is saved or not, return to the view
    return View();
}

通过检查 HttpContext.Request.HttpMethod 或使用 HttpPost 属性,可以确保 [HttpPost] 方法仅在提交表单时执行,而不是在视图初始加载时执行。在上面的例子中,[HttpPost]方法内部的逻辑只有在请求是POST请求时才会被执行。

记得将[HttpPost]方法中的逻辑注释替换为你实际的数据保存逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.