【问题标题】:I am having issues sending data from a form post to my controller我在将表单帖子中的数据发送到我的控制器时遇到问题
【发布时间】:2016-02-16 19:21:47
【问题描述】:

我有一个应用程序应该接受来自我在 Index.cshtml 类中所做的表单帖子的 4 个参数。我将控制器设置为在查询数据库后返回一个 csv 文件。我正在使用表单发布但不确定我缺少什么,因为它没有向我的控制器发送任何数据以处理查询和下载文件。

This is my HTML 
<div id="engagementForm" class="col-lg-offset-4">
@using (Html.BeginForm ("GetClientList", "Home", FormMethod.Post) )
{   
    <div class="form-horizontal" role="form">
        <div class="form-group" id="marketSelection">
            <label class="control-label col-sm-2" name ="marketGroup" id="marketGroup">Engagement Market:</label>
            <div class="col-lg-10">
                <input id="mrkGroup">
            </div>
        </div>
        <div class="form-group" id="officeSelection">
            <label class="control-label col-sm-2" name ="engagementOffice" id="engagementOffice">Engagement Office:</label>
            <div class="col-sm-10">
                <input id="engOffice">
            </div>
        </div>
        <div class="form-group" id="partnerSelection">
            <label class="control-label col-sm-2" Name ="engagementpartner" id="engagementpartner">Engagement Partner:</label>
            <div class="col-sm-10">
                <input id="engPartner">
            </div>
        </div>
        <div class="form-group" id="statusSelection">
            <label class="control-label col-sm-2" Name ="engagementStatus" id="engagementStatus">Engagement Status:</label>
            <div class="col-sm-10">
                <input id="engStatus">
            </div>
        </div>
        <button class="k-button" type="submit" id="searchButton">Create Speardsheet</button>
    </div>

}

This is my Controller 
public ActionResult GetClientList(int? marketGroup, int? engagementOffice, int? engagementpartner, int? engagementStatus)
    {
        List<Engagement> QueryResult = PMService.GetRequestedEngagments(marketGroup, engagementOffice, engagementpartner, engagementStatus);        


        var writetofile = PMService.BuildCsvString(QueryResult);
        var bytefile = Encoding.UTF8.GetBytes(writetofile);


        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
        Response.Charset = "";
        Response.ContentType = "application/text";
        Response.Output.Write(writetofile);
        Response.Flush();
        Response.End();         

        return View();

    }

【问题讨论】:

  • name 属性添加到您的元素并确保它们与您在控制器中的参数名称相同。

标签: c# asp.net-mvc razor controller


【解决方案1】:

您的所有输入都没有name 属性:

<input id="mrkGroup">

因此浏览器无法在 POST 值的键/值对中识别它们。只需添加一些names:

<input id="mrkGroup" name="marketGroup">

旁注:返回一个FileResult 对象将首选直接写入MVC 中的Response 输出。您会发现调试和测试要容易得多。写入输出返回一个视图似乎...容易出错。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多