I have made a webapp where you search by client id, and then adds orders on that client. The index action method assigns the chosen client to the viewmodel(vm.AllClients). The order table of course has information about the client. In the Insert method i want to use the information about the chosen client, but now vm.AllClients is returning null.
During debugging vm.AllClients is filled with one client object, as it should, during the running of the first method. When the second method is running vm.AllClients is empty.
I have tried to save the search string as a variable and find it in the db(Not a good solution), but the variable is also empty during the running of the second method. Also tried to save the chosen client as a Client object in the viewmodel, still no dice.
AddController
using MainWeb.Models;
public class AddController : Controller
{
OrderEntities db = new OrderEntities();// New instance of db.
ViewModel vm = new ViewModel();//New instance of viewmodel
[HttpPost]
public ActionResult Index(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm))
{
vm.AllClients = new List<Client>();
}
else
{
vm.AllClients = db.Clients.Where(x =>
x.RefNo.ToString().Equals(searchTerm)).ToList();
foreach (Client client in vm.AllClients)
{
vm.ThisClient = client;//Attempt at a different solution
break;
}
}
return View(vm);
}
public ActionResult InsertOrder(FormCollection form)
{
Order order = new Order();
order.ClientID = vm.AllClients[0].ID;//Here is where the error gets thrown
return RedirectToAction("Index");
}
View
@model MainWeb.Models.ViewModel
<div class="card border-primary mb-3 card-client" style="max-width: 40rem;">
<div class="card-header">Legg til</div>
<div class="card-body">
<div class="editor-label">
<table>
@using (Html.BeginForm("Test", "Add", FormMethod.Post))
{
<tr>
<td>@Html.Label("Velg Prosjekt:")</td>
</tr>
<tr>
<td>
@Html.DropDownList("fromDBProjects", (IEnumerable<SelectListItem>)ViewData["DBProjects"], new { @class = "form-control" })
</td>
</tr>
<tr>
<td>@Html.Label("Velg Produkt:")</td>
</tr>
<tr>
<td>
@Html.DropDownList("fromDBProducts", (IEnumerable<SelectListItem>)ViewData["DBProducts"], new { @class = "form-control" })
</td>
</tr>
<tr>
<td>@Html.Label("Pris:")</td>
</tr>
<tr>
<td><input type="submit" value="Submit" class="btn btn-primary" id="btn-search" /></td>
</tr>
}
</table>
</div>
</div>
</div>
</div>
}
ViewModel
namespace MainWeb.Models
{
public class ViewModel
{
public List<Client> AllClients { get; set; }
public Client ThisClient { get; set; }
}
}
Error:
Object reference not set to an instance of an object