Friday, June 24, 2016

MVC: Passing objects from main view to partial view

There are many ways to pass object from view to partial view, the following is an example how to pass object throw strong type model.

Suppose you have main page, which has Message partial view. Message is used to display messages and it should be shared between other views.

You have to create Model for Message which includes the following:
1. Message, which is message text
2. Type, message type to control the message css class, errors, success, notifications ... etc

Then you need to create View with strong type Message, and don't forget to check Partial View when you create the view.

put the following lines in the partial view:
@if(Model != null)
{
<div>
    @Model.Message
</div>
}

After that, create a controller and leave it as is.

In the main View. you will have the following:
@model Tuple<EventsRegistrations.Users.Model.ProfileInfo, EventsRegistrations.MVC.Models.Shared.Messages>

@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>View1</title>
</head>
<body>
    @Html.Partial("Message", Model.Item2)
    <br />
    @Html.Partial("Profile", Model.Item1)
</body>
</html>


And in the controller set the following:
public Messages msg = new Messages();
        public EventsRegistrations.Users.Model.ProfileInfo obj = new Users.Model.ProfileInfo();

        public ViewResult DisplayProfile()
        {
            try
            {
                obj = EventsRegistrations.Users.BLL.Profile.Instance.Get(1);
                throw new Exception("ex");
                return View("Index", Tuple.Create(obj, msg));
            }
            catch (Exception ex)
            {
                msg.Message = MessageHelper.BuildExceptionMessage(ex);
                msg.Type = 1;
                return View("Index",Tuple.Create(obj, msg));
            }
        }


No comments:

Post a Comment