I have a view with multiples forms, each one submit should submit a hidden field with a specific value and all of the share the same model. From my controller I set the value before rendering the view, but that value I will need it for one of the "Post" methods, the others should submit the same hidden field but with a different value.
Here I am displaying just the second form of the view with the hiddenInput EventCommand
@using (Html.BeginForm("ContinueWithUpload", "Odometer", FormMethod.Post, new { id = "form2" }))
{
@Html.HiddenFor(m => m.EventCommand)
<div>
<button type="submit" name="upload-excel" value="upload-excel" id="excel-upload" class="btn btn-success">Continue Upload</button>
</div>
}
so far I tried to set it in javascript but it doesn't work
$(function(){
$("#excel-upload").on("click", function (e) {
$("#EventCommand").val("upload-excel");
});
}
reading about how to do it, I found a solutions with the ViewData, but also with that workaround it doesn't work
@Html.HiddenFor(m => m.EventCommand)
ViewData["EventCommand"] = "upload-excel"
Any help will be appreciated
Because the html that Razor renders is the same for my HiddenInput using the same model. I put my hidden inputs in a Partial View "_HiddenFields" and before rendering it, I passed a value of ViewDataDictionary. With that it allowed me to put a restriction on the PartialView of which html I wanted to generate. Below is the idea:
@using (Html.BeginForm("ContinueWithUpload", "Odometer", FormMethod.Post, new { id = "form2" }))
{
@Html.Partial("HiddenFields/_HiddenFields", Model, new ViewDataDictionary { { "EventCommand", "excel-upload"} })
}
and my partial view is like this
@if ((string)Html.ViewData["EventCommand"] == "excel-upload")
{
@*@Html.HiddenFor(m => m.EventCommand)*@
@*@Html.HiddenFor(m => m.EventCommand, new {@value = "excel-upload"})*@
<input id="EventCommand" name="EventCommand" type="hidden" value="excel-upload" />
}
else
{
@Html.HiddenFor(m => m.EventCommand)
}
if you see I commented the first two lines because both of them are not working even if the ViewData has the same key as the field EventCommand.