0

我有一个包含多个表单的视图,每个提交都应该提交一个具有特定值的隐藏字段,并且所有表单都共享相同的模型。在我的控制器中,我在渲染视图之前设置了该值,但是对于“发布”方法之一,我需要它,其他方法应该提交相同的隐藏字段但具有不同的值。

在这里,我仅使用 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>
}

到目前为止,我尝试在 javascript 中设置它,但它不起作用

$(function(){
    $("#excel-upload").on("click", function (e) {  
        $("#EventCommand").val("upload-excel");
    });
}

阅读有关如何执行此操作的信息,我找到了 ViewData 的解决方案,但使用该解决方法它也不起作用

@Html.HiddenFor(m => m.EventCommand)
ViewData["EventCommand"] = "upload-excel"

任何帮助将不胜感激

4

3 回答 3

1

看起来您有多个具有相同 ID 的隐藏文件,当您单击按钮时,您的代码无法选择正确的文件。您应该尝试在单击按钮的表单中获取确切的隐藏字段:

$(function()
{    
    $("#excel-upload").on("click", function (e) {  
        $(this).parents("form #EventCommand").val("upload-excel");
        return true;
    });
}
于 2017-01-21T04:24:16.843 回答
0
Use following code:

@using (Html.BeginForm("ContinueWithUpload", "Odometer", FormMethod.Post, new { id = "form2",onsubmit = "return myJsFunction(this)" }))
{   
    @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>
}


Add following javascript function:

function myJsFunction(this)
{
$(this).find('#EventCommand').val("upload-excel");
        return true;
}
于 2017-01-23T09:49:37.033 回答
0

因为 Razor 呈现的 html 对于我使用相同模型的 HiddenInput 是相同的。我将隐藏的输入放在部分视图“_HiddenFields”中,在渲染它之前,我传递了一个 ViewDataDictionary 的值。有了它,我可以对要生成的 html 的 PartialView 进行限制。下面是思路:

@using (Html.BeginForm("ContinueWithUpload", "Odometer", FormMethod.Post, new { id = "form2" }))
{
    @Html.Partial("HiddenFields/_HiddenFields", Model, new ViewDataDictionary { { "EventCommand", "excel-upload"} })
}

我的部分观点是这样的

@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)
}

如果您看到我评论了前两行,因为即使 ViewData 与字段 EventCommand 具有相同的键,它们都不起作用。

于 2017-01-23T17:21:04.770 回答