Souvik Ghosh
Souvik Ghosh

Reputation: 4606

Pass HTML hidden field value in @HTML.BeginForm

I want to pass a hidden field value on click of submit button into my action method. This needs to happen on click of a button which posts a file. Below is the Razor code for HTML form with Post method that accepts the file.

@using (Html.BeginForm("UploadProject", "Admin", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
        <label id="lblProjectSize" hidden="hidden">Select Project size</label>
        <select id="ddlProjectSize">
            <option value="1">Large</option>
            <option value="2">Medium</option>
            <option value="3">Small</option>
        </select>
    <input type="hidden" id="hdnProjectSize" />
    <input type="submit" value="Upload Data" onclick="setHiddenVal()" />
}

This is the action method I have-

[HttpPost]
public async Task<ActionResult> UploadProject(string UploadProjectOption, int? ProjectId, HttpPostedFileBase PostedFile)
{
    //code here
}

I am able to access the file object in the action method but I am not sure how to pass an additional parameter through the submitted form.

As of I am setting the the hidden field value on click of submit button after which I need to access the hidden field value in the posted action method.

Script to set hidden field value-

function setHiddenVal()
{
    alert($("#ddlProjectSize :selected").val());
    $("#hdnProjectSize").val($("#ddlProjectSize :selected").val());
}

I don't wan't to use AJAX for this.

Upvotes: 1

Views: 4398

Answers (1)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

Firstly, you should set name attribute for input types and you defined onclick event on the submit and of course you can't trigger the form action. Define onchange event for select option instead.

@using (Html.BeginForm("UploadProject", "Admin", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
    <label id="lblProjectSize" hidden="hidden">Select Project size</label>
    <select id="ddlProjectSize" name = "ddlProjectSize" onchange="setHiddenVal()">
        <option value="1">Large</option>
        <option value="2">Medium</option>
        <option value="3">Small</option>
    </select>
    <input type="hidden" id="hdnProjectSize" name = "hdnProjectSize"/>
    <input type="submit" value="Upload Data" />
}

Upvotes: 1

Related Questions