Quote:
On loading it takes more time.I want to load data after clicking a button not in page loading.
As per above, to keep it simple, I've put together a Proof-of-Concept project. You can swap out my data and handling of your view data for your own testing.
Note: This is not an Ajax solution as it was not stipulated in the question.
Data Object to share with the view:
public class TestData
{
public bool IsLoaded { get; set; }
public List<string> Answers1 { get; set; }
public List<string> Answers2 { get; set; }
public List<string> Answers3 { get; set; }
}
Controller:
public class HomeController : Controller
{
[HttpPost]
public ActionResult TestListPost(TestData request)
{
TempData["load"] = request?.IsLoaded;
return RedirectToAction("TestList");
}
[HttpGet]
public ActionResult TestList()
{
if (TempData.ContainsKey("load") &&
!string.IsNullOrWhiteSpace(TempData["load"].ToString()))
{
return View(new TestData
{
Answers1 = new List<string>
{
"Answer 1 - 1",
"Answer 1 - 2",
"Answer 1 - 3"
},
Answers2 = new List<string>
{
"Answer 2 - 1",
"Answer 2 - 2",
"Answer 2 - 3"
},
Answers3 = new List<string>
{
"Answer 3 - 1",
"Answer 3 - 2",
"Answer 3 - 3"
},
IsLoaded = true
});
}
return View(new TestData());
}
}
The View:
@model WebApplication1.Models.TestData
@{
ViewBag.Title = "TestList";
}
<h2>TestList</h2>
@if (!Model.IsLoaded)
{
Model.IsLoaded = true;
using (Html.BeginForm("TestListPost", "Home", FormMethod.Post))
{
<button type="submit">Load Answers</button>
}
}
else
{
<p>Results</p>
if (Model.Answers1 != null) { @Html.Partial("Answers", Model.Answers1); }
if (Model.Answers2 != null) { @Html.Partial("Answers", Model.Answers2); }
if (Model.Answers3 != null) { @Html.Partial("Answers", Model.Answers3); }
}
And the Partial View:
<ul>
@foreach (var item in Model)
{
<li>@item.ToString()</li>
}
</ul>
How it works:
1. When the view
TestList
action is initially loaded, only a button is shown. The view sets the
Model.isLoaded = true
ready for postback
2. Clicking the button posts the model back to the controller's action
TestLoadPost
3. the
TestLoadPost
sets a temporary state variable in the
TempData
PropertyBag and redirects back to the form load action
TestList
4. The
TestList
action checks if it needs to load the data and performs the task if the temp value is set
5. The view now loads and displays the data