ASP.NET MVC - how to reload same view after posting data?
like that
[HttpPost]
public void Index(String address)
{
TempData["address"] = address;
RedirectToAction("Index");
}
you see it blank because you are redirecting RedirectToAction("Index");
and storing data in TempData and u r not using it in the index Get method
[HttpGet]
public async Task<ActionResult> Index()
{
// I fetch the info from DB here put it inside ViewBag and call the view
// you must check for the temp data
if (!string.IsNullOrWhiteSpace(TempData["address"].ToString()))
{
ViewBag["result"] = TempData["address"];
//and use you viewbag data in the view
}
return View();
}
that mechanism I told u about ...
if I have an Address entity
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string House { get; set; }
public int Floor { get; set; }
}
and this is the controller actions AddressController
[HttpGet]
public ActionResult Index()
{
var model = new SearchAddressesViewModel();
// you can here also fetch all the addresses in your db ...
//but this is not a good approach also, but if you need to do that it's easy
// fetch data base and get all addresses
//model.AddressesFound = db.Addresses.Select(a => new AddressModel
//{
// Street = a.Street,
// House = a.House,
// Floor = a.Floor
//}).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(SearchAddressesViewModel model)
{
if (!ModelState.IsValid)
return View(model);
// fetch data base and get addresses based on the search criteria in
//model.SearchCriteria
// for example:
//var addresses = db.Addresses.Where(a => a.Street == model.SearchCriteria);
//add found addresses to model
//model.AddressesFound = addresses.Select(a => new AddressModel
//{
// Street = a.Street,
// House = a.House,
// Floor = a.Floor
//}).ToList();
return View(model);
}
and here is my View Index.cshtml
@model SearchAddressesViewModel
@using (Html.BeginForm("Index", "Address", FormMethod.Post))
{
@Html.LabelFor(m => m.SearchCriteria);
@Html.TextBoxFor(x=>x.SearchCriteria);
@Html.ValidationMessageFor(m => m.SearchCriteria, "");
<br />
<input type="submit" class="btn btn-block btn-success" value="Search" />
}
@if (Model.AddressesFound != null)
{
<table>
<thead>
<tr>
<th>Street</th>
<th>House</th>
<th>Floor</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.AddressesFound)
{
<tr>
<td>@item.Street</td>
<td>@item.House</td>
<td>@item.Floor</td>
</tr>
}
</tbody>
</table>
}
and here it the view model I used SearchAddressesViewModel
and AddressModel
public class SearchAddressesViewModel
{
[Required]
[Display(Name = "Search for address")]
public string SearchCriteria { get; set; }
public IList<AddressModel> AddressesFound { get; set; }
}
public class AddressModel
{
public string Street { get; set; }
public string House { get; set; }
public int Floor { get; set; }
}
also you can use partial view for AddressModel
in the view based on your case.
I hope that you got my point... thank you