基于某些逻辑显示和隐藏MVC视图部分的最佳方法是什么?

时间:2017-04-06 20:56:40

标签: asp.net-mvc

我刚才有一些我正在思考的东西以及我在很多代码中实现的东西,我认为这不是最好的做法。

您知道,在提交表单后,您可能希望直接返回同一页面并显示成功消息,并希望隐藏提交的表单输入。其他时候,您可以指向带有可选参数的页面,例如查询字符串,并且基于该参数,您可能希望在视图中显示和隐藏某些内容。

我不确定这样做的最佳方式,因为我喜欢将所有逻辑保留在我的控制器中而不是在我的视图中放置逻辑。

只需在不同的面板中分离元素并在cs控件中设置隐藏属性,即可在webforms中完成此操作。

我在MVC(我不喜欢)中这样做的方式是,例如,在我的视图中使用ViewBag成功消息和if语句来检查viewbag是否为null。如果它不为null,则显示成功消息;否则,它会显示一些表单输入。其他时候,您不使用viewbag。例如,购物车的结帐页面。在您的视图中,您可以检查购物车模型是否为空。如果是,则显示“抱歉,您的购物车是空的”消息;否则,显示购物车表。我不喜欢用我的视图中的逻辑来处理这个问题。什么是最好的解决方案?还有其他解决方案吗?

这里有一些示例代码。

控制:

 [HttpPost]
 public ActionResult Edit(Elephants elephants)
 {
     // do something with elephants 

     ViewBag.weldone = "Weldone, you have made a wonderful impact by submitting this crucial knformation about elephants to the world";
     return View();

 }

查看:

 @if(ViewBag.weldone != null)
 {
      <p>@ViewBag.weldone</p>
 }

 else
 {
      //something you want to hide from the page on succesfull elephant save

 }

1 个答案:

答案 0 :(得分:1)

不要使用ViewBag,而是使用视图模型 - 其名称为“模型视图控制器”。

public class Elephants
{
    ...
    public string SuccessMessage { get; set; }
}

[HttpPost]
public ActionResult Edit(Elephants model)
{
    // do something with elephants 

    model.SuccessMessage = "yay";
    return View(model);
}

并在视图中

@model Elephants

@if (model.SuccessMessage != null)
{
   <p>@model.SuccessMessgae</p>
}
else
{
   // Redisplay Elephants
}

@Html.ValidationSummary()

或者您可以通过重定向到另一个显示您的消息的页面来避免这一切。

[HttpPost]
public ActionResult Edit(Elephants model)
{
    // do something with elephants 

    return RedirectToAction("EditSuccess");
}

[HttpGet]
public ViewResult EditSuccess()
{
    return View();    // Displays view "EditSuccess.cshtml"
}