简体   繁体   中英

Best way to send message from controller to view in asp.net core mvc

I'm using asp.net core mvc (latest version).

I always send my messages (success or failed messages) from controller to view by TempData like this:

TempData["msg"] = "Operation was successful";

and in the view show this message to user:

@if (TempData["msg"] != null)
    {
        string msg = (string)TempData["msg"];
        <script>
            UIkit.notification({ message: '@msg', status: 'primary', pos: 'bottom-center', timeout: 15000 });
        </script>
    }

i want to know the standard (best and optimized) way to pass this kind of messages from controller to view.

is TempData good for this case? is there any better way?

Thanks.

You usually send a "Model" to your "View" through "Controller" that's what MVC stands for of course:

public class SendMessageModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    //... More stuff
}

//... inside controller
var model = new SendMessageModel()
{
    Id = 1,
    Name = "Name"
};

return View(model);

//... inside view
@model SendMessageModel


<span>@Model.Id @Model.Name</span>

but sometimes you need to send additional info to the view. This data is not necessarily part of the model. For this kind of scenario using ViewData is my choice.

public async Task<ActionResult> Index(bool? error)
{
    if (error == true)
    {
        ViewData["Message"] = "Some error message";
    }

    //....
    return View();
}

//... inside view
@model SendMessageModel
@{
    var msg = ViewData["Message"];
}

@if(msg != null)
{
    <span class="error">@msg</span>
}

of course, this is not the only way or "the best way". There's always another way to do this and that's the beauty of Asp.Net Core or programming in general.

Create a model to represent all data you are going to display in the view.

public class NewInvoiceViewData
{
    public Invoice Invoice { get; set; }
    public string Message { get; set; }
    public bool HasMessage => string.IsNullOrEmpty(Message) == false;
}

public async Task<ActionResult> CreateInvoice(NewInvoiceParameters parameters)
{
    var invoice = createInvoice.From(parameters);
    var message = invoice == null ? "Something gone wrong" : "Success";
    
    var viewData = new NewInvoiceViewData
    {
        Invoice = invoice,
        Message = message
    }

    return View(viewData);
}

In view

@if (@data.HasMessage)
{
    <script>
        UIkit.notification({ message: '@data.Message', status: 'primary', pos: 'bottom-center', timeout: 15000 });
    </script>
}

MVC(Model View Controller) is not about application layering. Model isn't required to be a business objects or database tables. Notice, that it can be a business object or database datable if no extra values are required, but it is not mandatory.

Model is an object which view know how to display without extra workarounds and model can have all data required and possible prepared for the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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