doosh
doosh

Reputation: 875

ASP.NET MVC: Passing a string to a view

I have a controller that looks like this:

public class PersonController : Controller
{
    public ActionResult Result()
    {
        var s = new PersonResult();
        s = GetPerson(ViewBag.PersonInfo);
        return View(s);
    }
[...]
}

The controller calls the view Result which looks like this:

@model My.Class.Library.DTO.PersonController
@if (Model != null && Model.Persons.Count > 0)
{
     @Html.Partial("Persons", @Model.Persons)
}

So the model can hold many Persons. Persons is sent to its own view like this (view Persons):

@using My.Class.Library.DTO

@model List<Person>

<section>
    @foreach (Person person in @Model)
    {
        @Html.Partial("Person", person)
    }
</section>

So I'm sending each Person person to my view Person. And in that view I'm drawing each Person like so:

@model Person
@if (Model.Fields.TryGetValue("description", out description)
{
    var descSplit = description.Split('#');
    foreach (string s in descSplit)
    {
        <div class="row-fluid">
            <div class="span2">Person</div>
            <div class="span10">@s</div>
        </div>
    }
}

But instead of doing that, I want to pass the string s to its own view. Something like this:

@model Person
@if (Model.Fields.TryGetValue("description", out description)
{
    var descSplit = description.Split('#');
    <section>
        @foreach (string s in descSplit)
        {
            @Html.Partial("Description", s)
        }
   </section>        
}

But "s" is just a primitive type: a string. How do I pass that to my view "Description"? What should my view "Description" look like? I'm thinking something like this:

@model string

    <div class="row-fluid">
        <div class="span2"><b>TEST</b></div>
        <div class="span10">@s</div>
    </div>

But that's not correct... What should my model be and how can I present the string (s) that I'm sending from the other view?

Upvotes: 1

Views: 1696

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38598

Your code looks right but in your partial view, try using the Model property.

@model string

    <div class="row-fluid">
        <div class="span2"><b>TEST</b></div>
        <div class="span10">@Model</div>
    </div>

When you strongly type your Views/PartialViews, you have to use the Model property to read the value you have passed as a Model to this View/PartialView.

Upvotes: 3

Related Questions