我需要发布一个表单,但是我还需要包括我要从模型集合中删除的小部件的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 />
}
这将显示:
我希望用户可以选择从列表中删除小部件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,但是我认为有比这更好的方法了?
答案 0 :(得分:1)
为了实现所需的功能,我使用带参数的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" });
编辑:
如果要将数据发布到控制器,则可以使用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);
}
}