我想创建一个对控制器操作的调用,只携带 id(从模型接收到的),而不是将整个模型传递给控制器。
我的型号是:
public class SingleProduct
{
[JsonProperty("product")]
public Product1 Product { get; set; }
}
public class Product1
{
[JsonProperty("id")]
public double? Id { get; set; }
[JsonProperty("title")]
public string? Title { get; set; }
[DisplayName("Body")]
[JsonProperty("body_html")]
public string? Body_html { get; set; }
}
这是我的观点:
@model SingleProduct
<div class="row">
<div class="col-md-4">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
@Html.LabelFor(model => model.Product.Title)
@Html.TextBoxFor(model => model.Product.Title)
</div>
<div class="form-group">
@Html.LabelFor(model => model.Product.Body_html)
@Html.TextBoxFor(model => model.Product.Body_html)
</div>
<form asp-action="DeleteProduct">
@Html.TextBoxFor(model => model.Product.Id)
<div class="form-group">
// this is the part causing error
@Html.ActionLink(
"Delete",
"DeleteProduct",
new { id = Product.Id })
<a href="Update_Delete/[email protected]">Confirm Delete</a>
<input type="submit" value="Delete" class="btn btn-primary" />
</div>
</form>
</div>
</div>
这是我的控制器操作:
[HttpPost]
// Any way to receive Product.Id without model?
public IActionResult DeleteProduct(long id)
{
// rest of the code
}
正如@GSerg 在上面的评论中所描述的,
Html.ActionLink
制作了GET
。因此,如果您想拨打 POST
,您可以拨打 jQuery
电话。
为此,将 jQuery Unobtrusive Ajax 包添加到您的项目中并更改视图代码:
@Html.ActionLink("Delete", "DeleteProduct", new { id = Product.Id })
到
<a data-ajax="true"
data-ajax-mode="replace"
data-ajax-method="post"
href='@Url.Action("DeleteProduct", "Delete", new { id = Model.Product.Id })'>
Delete
</a>