[英]How to send non-model data using a submit button (Razorpages)
我需要发布一个表单,但我还需要包含我想从模型集合中删除的小部件的 ID。 我可以通过提交传递额外的数据,这不是模型的一部分吗?
我使用 foreach 循环生成了 html。 这将显示小部件的 ID。 此页面的模型是小部件的集合。
因此用于显示所有小部件 Id 的代码如下:
@foreach (var widget in widgets){
@i++; // Assume declared above or could use simple for loop ...
Widget @widget.Id
<input type="hidden" asp-for="Widgets[i].Id" /> // For binding the collection on POST
<br />
}
这显示:
我希望用户可以选择从列表中删除 Widget 2。
所以显示将是这样的:
我想将模型发布回服务器并传递小部件的 ID...我该怎么做?
如果我使用如下所示的输入,我如何向其中添加 Id?
@foreach (var widget in widgets){
@i++; // Assume declared above or could use simple for loop ...
Widget @widget.Id
<input type="hidden" asp-for="Widgets[i].Id" /> // For binding the collection on POST
<input type="submit" asp-page-handler="RemoveWidget" name="x" />
<br />
}
我已经考虑过创建一个全局隐藏输入字段并在发送提交之前使用 javascript 将此字段设置为 Id,但我认为有比这更好的方法吗?
为了实现您想要的功能,我使用带有参数的 ActionLink:
@foreach (var widget in widgets){
Widget @widget.Id @Html.ActionLink("Delete", "Home", new { id = @widget.Id})<br />
}
在您的控制器中:
public ActionResult Delete(int id)
{
//Get your widget ID here and do the deletion as required.
return View("Your View");
}
您可以根据需要设置 ActionLink 的样式,如下所示:
@Html.ActionLink("Delete", "Home", new { id = @widget.Id},new { @style="your style goes here" });
编辑:
如果要将数据 POST 到控制器,可以使用 AJAX。 具体在您的情况下,我将向您展示一个示例:
@foreach (var widget in widgets){
Widget @widget.Id : <a href="#" data-id="@widget.Id" onclick="confirmDelete(this)"></a><br />
}
在你的 AJAX 中:
function confirmDelete(event) {
var recordToDelete = $(event).attr("data-id"); //Get your current widget id here
if (confirm("Are you sure you want to delete this widget") == true) {
//Prepare our data
var json = {
id: recordToDelete
};
$.ajax({
url: '@Url.Action("Delete", "Home")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json) },
success: function (data) {
if(data == "success") {
alert("Successfully deleted selected widget");
location.reload();
}
},
error: function (data) {
alert("Could not delete selected widget. Please try again!");
},
});
}
};
最后在您的控制器中:
//Delete a widget based on the ID that you get from your View
[HttpPost]
public JsonResult Delete(string json)
{
var serializer = new JavaScriptSerializer();
try
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string id = jsondata["id"];
if(id != "")
{
int getid = Convert.ToInt32(id);
//Call your db or your logic to delete the file
DatabaseAccess data = new DatabaseAccess();
string result = data.DeleteFile(getid);
if(result.Equals("Success"))
{
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("fail", JsonRequestBehavior.AllowGet);
}
}
else
{
return Json("notfound", JsonRequestBehavior.AllowGet);
}
}
catch
{
return Json("dberror", JsonRequestBehavior.AllowGet);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.