3

I want to pass a string variable to a partial view but im not sure how to display the string parameter to the partial view. I tried some answers i found on similar questions but i got the following output:

"my_app.Models.DogTreatments" . Can anyone tell me why is that?

Here is my code:

Controller:

[HttpPost]
    public ActionResult CasIndex(int Sid)
    {

        string treat = dbContext.DogTreatments.Where(x => x.Sid == Sid).SingleOrDefault().ToString();




        //  ViewBag.TList = dbContext.DogTreatments.Where(x => x.Sid == Sid);

        return PartialView("DisplayTreatments", treat);
    }

View page:

@Html.Partial("~/Views/Shared/DisplayTreatments.cshtml")

Partial view:

@model string

@{
    Layout = null;
}

@Model

1 Answer 1

1

What you see is correct because of your LINQ statement.

string treat = dbContext.DogTreatments.Where(x => x.Sid == Sid).SingleOrDefault().ToString();

This dbContext.DogTreatments.Where(x => x.Sid == Sid) filters all the DogTreatments Where x.Sid == Sid

This .SingleOrDefault() selects a single object of type DogTreatments or default(null).

The toString() will convert the object type to its string format hence my_app.Models.DogTreatments

Perhaps this would satisfies your requirement:

Return the object from LINQ query:

var treat = dbContext.DogTreatments.Where(x => x.Sid == Sid).SingleOrDefault();
return PartialView("DisplayTreatments", treat);

The Partial View will look like:

@using my_app.Models.DogTreatments //(this might need to be fixed)
@model DogTreatments

@{
    Layout = null;
}

// in here you can access the DogTreatments object
// These are just examples as I don't know from question what DogTreatments properties are
   @if(Model != null) 
   {
    @Model.Name 
    @Model.Treatment
   }
Sign up to request clarification or add additional context in comments.

1 Comment

If my answer has helped, please consider accepting it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.