Reputation: 114
I'm creating my first basic ASP MVC app based on a tutorial using a code-first approach.
I'm failing to understanding something in the controller/view context.
Ok, this is a part of my view script which contains a basic form:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.TextBoxFor(model => model.customerId, new { @Value = ViewBag.customerId })
@Html.EditorFor(model => model.customerEmailAddress)
<input type="submit" value="Next" />
}
Just a simple form with a couple of fields and a submit button.
This is my controller:
// GET
public ActionResult Index(int? customerId) // The customerId param is passed from the URL, irrelevant to the question
{
if(customerId == null)
{
customerId = generateCustomerId();
}
// At this point, I need to save this customer ID to the
// one of the Customer objects attributes, however,
// I cannot access the Customer object here?
return View();
}
// POST
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Customer Customer)
{
// This customer parameter represents the object model Customer
// which I use in my database schema - but where did it come from?
// How can I access this in my GET index actionresult above?
// ---
}
The comments in the code explain what I'm trying to do - where did the Customer object parameter come from in the post index method? Does it just automatically get generated and initialised by ASP? And how can I access this object in the GET Index method? I'm guessing I'll have to initialise it myself somehow?
Upvotes: 1
Views: 77
Reputation: 359
To explain it a slightly different way...
The form in the razor view will package up your model (with the changes you type in) and POST it to your second action - this is why the Customer object is a parameter - it will contain your updated customer data.
The first action expects you to implement a way to find a specific customer (with the id) and create a customer model then pass it to the view.
Upvotes: 1
Reputation: 3914
Q/where did the Customer object parameter come from in the post index method? A/ it's not automatically initialized via MVC, its going to come from the Form that you have in the index page when you submit it, then it will post to this Action method.
Q/And how can I access this object in the GET Index method? A/ you can't all what the Index have is a CustomerId, so based on that you can query the database to get that specific customer and do whatever you want with it.
Upvotes: 1