Question

this is my View containing an upload file control. so it needs "multipart/form-data" content type.

@using (Html.BeginForm("Create", "RoutinTest", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

<div>
            @Html.LabelFor(model => model.ScannedFile)
            <div>
                <input type="file" name="ScannedFile"  multiple="multiple" />
                @Html.ValidationMessageFor(model => model.ScannedFile)
            </div>
</div>
<div>
            <div>
                <input type="submit" value="Save"  />
            </div>
 </div>   

this is my controller and it's Create action methods:

[HttpGet]
 public ActionResult Create(string patientId, string fullName)
        {
            ViewBag.PatientId = patientId;
            ViewBag.FullName = fullName;
            return View();
        }

[HttpPost]
public ActionResult Create() RoutinTest routintest, string patientId, string fullName)
{

}

The problem is that On second Create action method (post method) both patientId and fullName are lost. (patientId = 0 and fullName = null) but I set both of them on Get method.

Amazingly when I change the form content type to it's default (by removing multipart/form-data), I am able to have those two parameters values. I know I can solve the problem without changing the form content type, by setting those two ViewBags value to hidden fields but I just want to know why this happens? What affect the "multiPart/form-data" form content type has on those ViewBags values?

thanks

Was it helpful?

Solution

Remember that your patientId and fullName is found in the URL. Reassigning them to the ViewBag has nothing to do with it (remove the ViewBag and see what happens)

// Looks familliar? This is your first request.
Create?patientId=0&fullName=

The parameters is passed to the second Create action method by default because the URL parameters is maintained.

// By default, parameters are not cleared during the second request.
Create?patientId=0&fullName=

When you set enctype = "multipart/form-data", the URL parameters gets cleared, resulting in something like this.

Create

Which means that it is the parameters that are lost and not the ViewBag data.

Related Problem: Form Post with enctype = "multipart/form-data" causing parameters to not get passed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top