0

Here is a partial views may display in many pages,and I use @Html.Partial to insert it to the page.

Now I want to change the text of partial views in controller.

Here is the code of index.cshtml:

@{
    ViewData["Title"] = "Home Page";
}

@Html.Partial("Aside.cshtml")

Here is the code of HomeController:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

public IActionResult About()
{
    ViewData["Message"] = "Your application description page.";

    return View();
}

public IActionResult Contact()
{
    ViewData["Message"] = "Your contact page.";

    return View();
}

public IActionResult Aside()
{
    return View();
}

public IActionResult Error()
{
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}

And here is the file list of my project:
enter image description here

When the project runs,and index.cshtml loaded,I found the IActionResult Aside() did not ran,but IActionResult Index() had ran.

As I said top of this question,I want to change the text of partial views(aside.cshtml) in controller,but now I can't for the IActionResult Aside() did not ran.

Why it did not ran?And how can I solve this problem?

Please help me,thank you.

RonC
  • 31,330
  • 19
  • 94
  • 139
Melon NG
  • 2,568
  • 6
  • 27
  • 52
  • What you mean by changing the text of partial view ? `@Html.Partial("Aside.cshtml")` will not invoke the the action method, but renders the partial – Shyju Apr 28 '18 at 16:58

1 Answers1

1

Constructed this way IActionResult Aside() will only run if the /aside url is requested, but doing that uses the partial as though it were a full view. If aside.chstml is to be a partial then the home controller should not have an IActionResult Aside() action method since partials don't have action methods.

If you want the controller to affect the partial then one way to do it is to have the controller set a value in the context items collection and have the partial access that value in the context items collection by injecting the current context into the partial. But some developers may think of this as a bit messy and prefer that the controller not modify the partial.

Alternatively, and this is probably the best approach, you could supply data to the view (for example with a view model) and then have the view pass that data to the partial @Html.Partial("Aside.cshtml", someData). You can learn more about this approach here: Pass parameter to Partial View in ASP.NET Core

RonC
  • 31,330
  • 19
  • 94
  • 139