0

I have this simple list of users in my model. If we click one user, I would like to set that user as the chosen one and refresh the partial view. My code looks like:

<div id="myPartialView">
@if (@Model.ChosenUser != null)
{
    @Model.ChosenUser.UserName
}                        

<ul>    
    @foreach (var u in Model.Users)
    {
        <li>
            <a href='@Url.Action("ChooseUser", "Controller", new { userId = u.UserId })'>@u.UserName</a>

        </li>
    }
</ul>

The controller method returns an Ok(); My current code redirects me to an empty page and I have to go back and refresh the page in order to see the model changes.

My question is, how can I refresh only this partial view after the razor action?

ARN88
  • 3
  • 2

1 Answers1

0

You will need to use Ajax.ActionLink here :

@foreach (var u in Model.Users)
{
    <li>
        @Ajax.ActionLink(u.UserName, // <-- Text to display
             "Choose User", // <-- Action Name
             "Controller", // <-- Controller Name
             new AjaxOptions
             {
                 UpdateTargetId="myPartialView", // <-- DOM element ID to update
                 InsertionMode = InsertionMode.Replace, // <-- Replace the content of DOM element
                 HttpMethod = "GET" // <-- HTTP method  
             })
   </li>
}

The helper method would render the html needed to create the anchor tag element with the specified values, and you need to make sure that you have scripts added in the master layout for unobtrusive ajax.

For that you can look here, what scripts are needed to be pre-requisite:

How to use Ajax.ActionLink?

and your action method should be returning the model of the same type that your partial view expects with data populated in the model.

Please refer to the following post to learn in detail about Ajax Action Link:

http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/ajax-actionlink-and-html-actionlink-in-mvc/

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160