Reputation: 5846
I have an MVC form (MyAction1) that contains textboxes, dropdowns, checkboxes, etc. The form is generated using a strongly typed View Model. I need to submit the form values to another page (MyAction2) in the same Controller.
It seems like FormMethod.Get is an appropriate choice to submit MyAction1's form values to MyAction2's GET Controller Action? Maybe it should be FormMethod.Post to call MyAction1's POST Controller Action and then redirect to MyAction2's GET Controller Action?
Either way, the form values are not available in MyAction2's GET Controller Action. I've traced the code as well as used Fiddler to confirm this.
I'm fine with using jQuery to intercept the form submit. I've attempted this without success. There are quite a few form controls and so I prefer to not create the querystring manually.
How is this done?
MyAction1's View:
@model My_Web_App.Models.MyAction1ViewModel
@using (Html.BeginForm("MyAction2", "MyController", FormMethod.Get))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-horizontal">
<!-- Project Name -->
<div class="form-group">
@Html.LabelFor(model => model.ProjectName, { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.EditorFor(model => model.ProjectName, new { @class = "form-control" } })
</div>
</div>
</div>
<div class="form-group">
<div class="well col-md-offset-4 col-md-4">
@Html.ActionLink("Submit", "MyAction2", new { Controller = "MyController" },
new { hidefocus = "hidefocus", id = "btnConsiderSpecificModel",
@class = "btn btn-default btn-block",
role = "button",
type = "submit" })
</div>
</div>
}
In MyAction2's GET Controller Action:
// GET: MyController/MyAction2/
public ActionResult MyAction2(MyAction1ViewModel formmodel)
{
MyAction2ViewModel model = new MyAction2ViewModel();
model.ProjectName = formmodel.ProjectName;
}
Using this approach, formmodel
is full of nulls, 0, and false values. It seems that MyAction1 View is not passing the form variables at all.
Upvotes: 0
Views: 1141
Reputation: 60438
The FormCollection
only works on POST
request.
There are several methods to get the data on GET
requests.
Why not use your already created view model ?
public ActionResult MyAction2(MyAction1ViewModel model)
{
model.ProjectName = model.ProjectName;
}
You can simple add the name of the variable to your action method
public ActionResult MyAction2(string projectName)
{
MyAction2ViewModel model = new MyAction2ViewModel();
model.ProjectName = projectName
}
You can look in the Request.QueryString
collection.
public ActionResult MyAction2()
{
MyAction2ViewModel model = new MyAction2ViewModel();
model.ProjectName = Request.QueryString["ProjectName"];
}
Upvotes: 1
Reputation: 3228
Try this;
public ActionResult MyAction2(MyAction1ViewModel form)
{
You have a strongly typed view and controller is expecting MyAction1ViewModel
.
Upvotes: 1