[英]how to pass the model of my current view to a controllers post action
im trying to pass model via parameter with html.beginform to an action but it dont work, debuging the model appears null, dont understand why, my code>
看法
@model IEnumerable<GestorBd.Models.Receptor>
@{
ViewBag.Title = "Index";
}
<h2>Receptores</h2>
<br />
Mostrando @Model.Count() elemento(s).
<br />
<br />
@using (Html.BeginForm("ConvertThisPageToPdf", "Receptors", FormMethod.Post, htmlAttributes: new { parame = Model }))
{
<input type="submit" value="Convert
This Page To PDF" />
}
我的 controller 動作
[HttpPost]
public ActionResult ConvertThisPageToPdf(IEnumerable<Receptor> parame)
{
// get the HTML code of this view
string htmlToConvert = RenderViewAsString("Index", parame);
// the base URL to resolve relative images and css
String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
/// and go on
}
此代碼創建 html 標記(表單)您可以像這樣使用名稱 attr 編寫輸入
<input type="text" name="your-name" id="your-name" />
進入表格范圍
您的代碼存在一些問題。 首先,我相信您正在嘗試通過查詢字符串而不是在請求正文中將復雜的 model 發送到 POST 方法。 要通過查詢字符串傳遞參數,您需要通過RouteValueDictionary
而不是 HTML 屬性 object 添加它們。 HTML 屬性 object 用於向實際表單元素添加屬性,例如id
。
但是,我相信在請求正文中傳遞 object 會更好。 為此,您需要為每個受體 object 添加表格 HTML 元素,以將 model 屬性傳遞給服務器。 例如:
@using (Html.BeginForm("ConvertThisPageToPdf", "Receptors", FormMethod.Post, htmlAttributes: new { id = "receptorsForm" }))
{
<!-- Add the properties of your receptor objects -->
@for (int i = 0; i < Model.Count(); i++)
{
var receptor = Model.ElementAt(i);
<!-- Note the index @i denotes that you are sending an array of items -->
<input type="hidden" name="receptors[@i].Id" value="@receptor.Id" />
<input type="hidden" name="receptors[@i].Name" value="@receptor.Name" />
<input type="hidden" name="receptors[@i].Value" value="@receptor.Value" />
}
<input type="submit" value="Convert This Page To PDF" />
}
假設 C# model 為:
public class Receptor
{
public int Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
請注意,表單元素名稱必須與 controller 操作參數名稱匹配,才能發生正確的 model 綁定。 要糾正這個問題,您需要更改方法簽名以接受可枚舉的受體:
[HttpPost]
public ActionResult ConvertThisPageToPdf(IEnumerable<Receptor> receptors)
{
//...
}
我沒有測試過這段代碼,但希望它能讓你非常接近你所需要的。
為什么不使用隱藏輸入。 像這樣:
<input type="hidden" name="receptors" value="@Model" />
此輸入對您的用戶不可見,但會發送到 controller 操作。 你可以像這樣得到輸入值:
[HttpPost]
public ActionResult ConvertThisPageToPdf(IEnumerable<Receptor> receptors)
{
//...
}
或者您可以使用 HttpContext.Request.Form 獲取值:
var receptors = HttpContext.Request.Form["receptors"];
但還有一件事,為什么你使用 BeginForm,因為你可以使用 html 表單標簽和 asp.net 標簽助手,如果你想使用 BrginForm 出於某些原因,你可以添加這樣的隱藏輸入:
@Html.HiddenFor(m => m)
確保您傳遞給 BeginForm 的 arguments(動作名稱和 controller 名稱)是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.