Show a Message in MVC using TempData

2019-08-29 08:02发布

问题:

i want to show a message in asp.net mvc. for this, i create a partial view. name of this partial view is _feedback. in body of this partial view i write this codes.

@model MyProject.SharedTools.OperationStatus

@if (Model != null)
{
    if (Model.IsSuccess)
    {
        @:Model.Message;
    }
    else
    {
        @:Model.Message;
    }
}

i put this code in _layout file:

@Html.Partial("_feedback")

and when i want to see a message from controller, using this code:

 operationStatus = _provinceRepository.Save();
 if (operationStatus.IsSuccess)
 {
     TempData["OperationStatus"] = operationStatus;
     return RedirectToAction("Index");
 }

but i give this error:

The model item passed into the dictionary is of type 'MyProject.Models.ProvinceModel', but this dictionary requires a model item of type 'MyProject.SharedTools.OperationStatus'.

回答1:

Make sure that you have passed the correct model that your partial is expecting:

@Html.Partial("_feedback", Model.SomePropertyOfTypeOperationStatus)

If you do not specify a model as second argument to the Html.Partial helper, then it will automatically pass the model of the current view (which in your case is of type MyProject.Models.ProvinceModel) and that's why you are getting the error : your partial expects a model of type MyProject.SharedTools.OperationStatus.

Also it is not quite clear where you are using the TempData value that you stored in your controller inside your partial. Maybe it should be something like this:

@model MyProject.SharedTools.OperationStatus

@if (Model != null)
{
    @TempData["OperationStatus"]
}

or didn't you just mean to display directly the value you stored in TempData in your partial without using a model?

@TempData["OperationStatus"]