如何通过单击“删除”按钮从MVC 4 ASP.NET中的列表中删除记录,这里我不使用任何数据库,但我想从控制器中定义的列表中删除记录。没有任何数据库的情况下,可以使用删除操作从列表中删除记录
StudentController
public class StudentController : Controller
{
//
// GET: /Student/
public ActionResult Index()
{
List<StudentVM> students = new List<StudentVM>();
StudentVM obj1 = new StudentVM();
obj1.Name = "Zeeshan";
obj1.id = "1";
obj1.Address = "Lahore";
students.Add(obj1);
StudentVM obj2 = new StudentVM();
obj2.Name = "Zeshan";
obj2.id = "2";
obj2.Address = "Lahore";
students.Add(obj2);
return View(students);
}
public ActionResult Delete(string? i)
{
List<StudentVM> students = new List<StudentVM>();
var st = students.Find(c => c.id = i);
students.Remove(st);
return View("Index");
}
}
查看
@model List<Activity2.Models.StudentVM>
@{
ViewBag.Title = "Index";
}
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
</tr>
@foreach (var obj in Model)
{
<tr>
<td>@obj.id</td>
<td>@obj.Name</td>
<td>@obj.Address</td>
<td>@Html.ActionLink("Delete","Delete",new{i = obj.id}) </td>
</tr>
</table>
}
错误
错误1按顺序,类型'字符串'必须是不可为空的值类型 在通用类型或方法中将其用作参数“ T” 'System.Nullable'
错误3无法隐式转换类型“字符串”? '字符串'
答案 0 :(得分:0)
首先,由于错误消息明确表明您需要使用string
而不是string?
:
public ActionResult Delete(string i)
其次,您应该意识到,MVC是无状态的,因为HTTP是。因此,此代码不会按照您的期望删除记录。为了使此代码有效,您需要使用Session。像这样:
if(Session["StudentVM"] == null)
{
//Your Code
Session["StudentVM"] = students;
}
并且:
public ActionResult Delete(string i)
{
List<StudentVM> students = Session["StudentVM"] as List<StudentVM>;
var st = students.Find(c=>c.id=i);
//The rest of your code...
}
答案 1 :(得分:0)
您正在尝试使用C#8.0的功能(该功能尚未发布还),它是可空引用类型。为了解决错误,您必须将string? i
更改为string i
。
要从列表中删除项目,您必须在Index()
外部创建它并将其设为静态,以便其他Delete()
端点可以访问该列表。这样,每次有人访问控制器的索引时,就会有两个新学生添加到列表中(从长远来看,这可能不是您想要的行为,我只是在此代码上复制了您的代码):
public class StudentController : Controller
{
private static readonly List<StudentVM> _students = new List<StudentVM>();
public ActionResult Index()
{
StudentVM obj1 = new StudentVM();
obj1.Name = "Zeeshan";
obj1.id = "1";
obj1.Address = "Lahore";
_students.Add(obj1);
StudentVM obj2 = new StudentVM();
obj2.Name = "Zeshan";
obj2.id = "2";
obj2.Address = "Lahore";
_students.Add(obj2);
return View(students);
}
public ActionResult Delete(string i)
{
var student = _students.FirstOrDefault(c => c.id == i);
if(student == null){ /* Failed to find student */ }
_students.Remove(student);
return View("Index");
}
}
您的View代码似乎也有错误。 </table>
应该在foreach之外。