Skip to main content
 首页 » 编程设计

c#之在 Controller 中创建函数的 MVC 最佳实践

2024年02月20日10kevingrace

<分区>

我仍在学习 MVC 编程,有一个问题要请您为我澄清一件事,即我的 Controller 中的 Get 和 POST ActionResult 函数。我会给你三种可能的情况(实际上是三个问题):

我的第一个场景:

public ActionResult Derp() 
{ 
    Derpina derpina = new Derpina(); //Should I need to pass this to View? 
    return View(derpina); 
} 
 
[HttpPost] 
public ActionResult Derp() 
{ 
    Derpina derpina = new Derpina(); 
    UpdateModel(derpina); 
    //doStuff and save to DB 
    return RedirectToAction("Index"); 
} 

我的第二种情况:

public ActionResult Derp() 
{ 
    return View(); 
} 
 
[HttpPost] 
public ActionResult Derp() 
{ 
    Derpina derpina = new Derpina(); //Is this the cleanest way? 
    UpdateModel(derpina); 
    //doStuff and save to DB 
    return RedirectToAction("Index"); 
} 

我的第三种情况:

public ActionResult Derp() 
{ 
    Derpina derpina = new Derpina(); 
    return View(derpina); 
} 
 
[HttpPost] 
public ActionResult Derp(Derpina derpina) 
{ 
    UpdateModel(derpina); //Should I need to do that at all? 
    //doStuff and save to DB 
    return RedirectToAction("Index"); 
} 

我倾向于第二种情况,因为我不需要创建新实体并将其传递给 View 。我想这就是我问你们的原因,有人曾经告诉我没有“愚蠢的问题”,所以我希望你们能忍受我:)

  1. 我是否需要将新创建的 Derpina 传递给 View
  2. 第二种情况不是“最佳实践”吗?
  3. 在第三种情况下,如果我将 Derpina 作为参数传递给 HttpPost 函数,MVC 框架是否尚未更新模型?

Englis 不是我的母语,所以我希望这些问题能说明问题。无论如何,提前感谢您能给我澄清的任何帮助。

已编辑

收到一个答案后,我想添加第四个场景:

public ActionResult CreateDerp() 
{ 
    return View(); 
} 
 
[HttpPost] 
public ActionResult CreateDerp(Derpina derpina) 
{ 
    UpdateModel(derpina); 
    //doStuff and save to DB 
    return RedirectToAction("Index"); 
} 

这是正确的方法吗,我的意思是如果我不需要在 GET 函数中将模型发送到 View ?例如,如果我像上面的代码建议的那样使用 Create 函数。