2017-08-17 86 views
2

我不完全理解的剃刀语法所以这是我的问题的一部分,但我也觉得没有用,我怎么想这样做一个逻辑问题,在C#中的功能来运行代码。获取提交按钮使用MVC 5

当我点击下载我刚刚获得“资源不能找到”

下面是从视图我的代码。

<td> 
     @Html.ActionLink("Edit", "Edit", new { id=item.cusName }) | 
     @Html.ActionLink("Details", "Details", new { id=item.cusName }) | 
     @Html.ActionLink("Delete", "Delete", new { id=item.cusName }) 


     <br /> 

    @using (Html.BeginForm("Download", "RMAFormModelsController", FormMethod.Post, new { id = "Download" })) 
    { 
     <div id="convertAboutPageButtonDiv"> 
      <input type="submit" value="Download to Excel File" /> 
     </div> 
    } 
    <br /> 

    </td> 

下面是来自C#函数的代码。

//Export to excel 
     [HttpPost] 
     public ActionResult Download() 
     { 

      List<Lookup> lookupList = new List<Lookup>(); 
      var grid = new System.Web.UI.WebControls.GridView(); 

      grid.DataSource = lookupList; 
      grid.DataBind(); 

      Response.ClearContent(); 
      Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xlsx"); 
      Response.ContentType = "application/vnd.ms-excel"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 
      grid.RenderControl(htw); 
      Response.Write(sw.ToString()); 
      Response.End(); 

      return View(); 
     } 

这一切似乎应该工作。我在想什么 - 理解?

+0

它似乎想要_RMAFormModels_无控制器部分,没有argiment _id =“下载” _通过下载方法 – Steve

+0

预期如果我理解你纠正你的说法。因为我没有争论,我应该试着直接引用模型?我认为视图必须与控制器通信并从模型中获取信息?感谢您的快速响应和您的帮助。 –

回答

3

更新RMAFormModels代替RMAFormModelsController的形式的HTML帮手。

@using (Html.BeginForm("Download", "RMAFormModels", FormMethod.Post)) 
    { 
     <div id="convertAboutPageButtonDiv"> 
      <input type="submit" value="Download to Excel File" /> 
     </div> 
    } 
+0

谢谢你这么多的工作!你介意解释它为什么起作用吗?如何调用模型允许我在控制器中运行该功能? –

+0

@JonathanGreene语法形式是Html.BeginForm(ActionName,控制器名称,方法类型)..所以,如果你的控制器的名字就像是abccontroller,那么你需要提及的表单中的ABC。 –

1

@Jonathan,你在你的代码中有两个问题。首先,您不必在html.beginform()中使用完整的控制器名称。从表单中删除RMAFormModelsController并仅添加RMAFormModels。

@using (Html.BeginForm("Download", "RMAFormModels", FormMethod.Post, new { id = "Download" }))) 
    { 
     <div id="convertAboutPageButtonDiv"> 
      <input type="submit" value="Download to Excel File" /> 
     </div> 
    } 

并在您的beginform中创建了新的{id =“Download”}。所以为了按预期工作,你的控制器中必须有一个名为id的参数。

[HttpPost] 
     public ActionResult Download(string id) 
     { 
     } 

否则,您可以使用@Power答案,因为他从html.beginform中删除了新的{id =“Download”}。

谢谢。