简体   繁体   English

MVC将数据从模型传递到视图

[英]MVC passing data from model to view

Actually I have a controller action and it gets the value of the variable 'result' from the function in a model. 实际上,我有一个控制器操作,它从模型中的函数获取变量“结果”的值。 The action is as below. 动作如下。

if (model.buildingID == 0)
{
    var result = objAddBuildingBusinessModel.AddBuilding(model, connectionstring,isUnique);                       
}
else
{
    var result = objAddBuildingBusinessModel.UpdateBuilding(model, connectionstring);
}

So now based on the value of the variable 'result' I have to display a error message in the view if the value of variable 'result' is false. 因此,现在基于变量“结果”的值,如果变量“结果”的值为false,则必须在视图中显示错误消息。 Where in view should I display that and how should I do it . 我应该在哪里显示它以及应该如何显示。 Please help me as I am new to MVC 请帮助我,因为我是MVC的新手

Store result output in viewbag and on view side check viewbag value and show error message: 结果输出存储在viewbag中,并在视图侧检查viewbag值并显示错误消息:

Note: ViewBag will hold your variable for single view request 注意: ViewBag将保存您的变量以用于单个视图请求

Controller: 控制器:

ViewBag.Result=result;

View: 视图:

@if(ViewBag.Result)
{
    //Eroor Message HTML
}

JQuery/Javascript: jQuery / Javascript:

$(document).ready(function () {
    if (String('@ViewBag.Result').toUpperCase() == "TRUE")
    {
        alert('Error Message');
    }
});

I think, you can create a model to keep same information then your data send to view any transfer method and show Exception. 我认为,您可以创建一个模型来保留相同的信息,然后发送数据以查看任何传输方法并显示Exception。

EnumClass 枚举类

Create Class EnumDefinitions. 创建类EnumDefinitions。 You can use all enum on this class inside. 您可以在此类内使用所有枚举。 Write all enums in namespace. 将所有枚举写入名称空间。 You can access this OperationEnum.FAIL or OperationEnum.SUCCESS 您可以访问此OperationEnum.FAILOperationEnum.SUCCESS

    [Obsolete("Dont Use", true)]
    internal static class EnumDefinitions
    {
       // dont use this.
    }


    /// <summary>
    /// Operation Enums
    /// </summary>
    public enum OperationEnum
    {
        FAIL = 0,
        SUCCESS = 1,
    }

Create Model 建立模型

public class OperationResult
{
    /// <summary>
    /// Operation fail code
    /// </summary>
    public static string FAIL = "0";

    /// <summary>
    /// Operation success code
    /// </summary>
    public static string SUCCESS = "1";

    /// <summary>
    /// 1 : Success
    /// 0 : Fail 
    /// Maybe you can use Enum to set ResultCode.
    /// </summary>        
    public string ResultCode { get; set; }

    /// <summary>
    /// Exception message
    /// </summary>         
    public string ResultMessage { get; set; }


}

Catch Exception 捕获异常

Use code in try catch block and catch exception.Send data to view using any data transfer method ( ViewBag , vs vs ) or using jsonResult 在try catch块中使用代码并捕获异常。使用任何数据传输方法(ViewBag,vs vs)或使用jsonResult发送数据以进行查看

 OperationResult resultData = new OperationResult();

    try
    {
      if (model.buildingID == 0)
      {
        var result = objAddBuildingBusinessModel.AddBuilding(model, connectionstring,isUnique);                       
      }
      else
      {
        var result = objAddBuildingBusinessModel.UpdateBuilding(model, connectionstring);
      }
      //resultData.ResultCode = OperationResult.SUCCESS;
      resultData.ResultCode = (int)OperationEnum.SUCCESS;
      resultData.ResultMessage = "Opetaion Success";
    }
    catch(Exception ex)
    {
       //resultData.ResultCode = OperationResult.FAIL;
       resultData.ResultCode = (int)OperationEnum.FAIL;
       resultData.ResultMessage = ex.Message;
    }
   // return resultData on viewBag or andy transafer data to view 
    ViewBag.ResultData = resultData;

Show Exception 显示例外

Best practice get operation value to Enum ( success or fail ) You can use as examples hardcode or use enum value if use enum value so that you can reach through the same enum values ​​on both sides 最佳做法是将操作值枚举为Enum(成功或失败),您可以使用硬编码作为示例,也可以使用enum值(如果使用enum值),这样您就可以在两侧通过相同的enum值

if ('@ViewBag.ResultData.ResultCode' ==  '@(int)OperationEnum.FAIL') // or "2"
{
    var exMessage = '@ViewBag.ResultData.ResultMessage';
    alert(exMessage );
}

first use Viewbag 首次使用Viewbag

 ViewBag.ans = "result";

then in the model section 然后在模型部分

  @model IEnumerable<MVCApp.Models.ModelName>
<b>Result:</b> @ViewBag.ans<br />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM