MVC3: button to send both form (model) values and

2019-05-08 21:22发布

问题:

In an MVC3 project, i use an Html.BeginForm to post some (model-)values. Along with those i want to send an extra parameter that is not part of the form (the model) but in the ViewBag. Now, when i use a Button (code in answer here: MVC3 razor Error in creating HtmlButtonExtension), all the form values are posted but the extra parameter remains null. When i use an ActionLink, the parameter is posted but the form values are not :) Any know how i can combine the two? Thanks!

@Html.Button("Generate!", new { id = ViewBag.ProjectID })
@Html.ActionLink("Generate!", "Post", new { id = @ViewBag.ProjectID })

回答1:

My advice would be to declare a new Object in your App.Domain.Model something like this

namespace App.Domain.Model
{
    public class CustomEntity
    {
        public Project projectEntity { get; set; }
        public int variableUsed { get; set; }
    }
}


In your view you can acces them easily by using CustomEntity.projectEntity and CustomEntity.variableUsed.

Hope it helps



回答2:

You can do something like below.

View code

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @id = "frmId", @name = "frmId" }))
{
        @*You have to define input as a type button not as a sumit. you also need to define hidden variable for the extra value.*@
        <input type="hidden"  name="hndExtraParameter" id="hndExtraParameter" />
        <input value="Submit" type="button" id="btnSubmit" onclick="UpdateHiddenValue()" />
}

<script type="text/javascript">

function ValidateUser() {
$("#hndExtraParameter").val('Assignvaluehere');
$("#frmId").submit();
}

</script>

Controller Code

[HttpPost]
public ActionResult ActionName(Model model, string hndExtraParameter)
{
//Do your operation here.
}