我有一个带索引和详细信息视图的MVC应用程序。索引显示_peticiones列表项。我想从详细信息视图更新此列表。
详细信息视图
@using (Html.BeginForm())
{
<div class="form-group">
<label for="id">Id:</label>
@Html.TextBoxFor(m => m.Id, new { @id = "id", @class = "form-control", @readonly = "readonly" })
</div>
<div class="form-group">
<label for="nombre">Nombre:</label>
@Html.TextBoxFor(m => m.Nombre, new { @nombre = "nombre", @class = "form-control"})
</div>
<div class="form-group">
<label for="desc">Descripcion:</label>
@Html.TextBoxFor(m => m.Desc, new { @dec = "desc", @class = "form-control"})
</div>
<div class="form-group">
<label for="fecha">Fecha:</label>
@Html.TextBoxFor(m => m.Fecha, new { @fecha = "fecha", @class = "form-control"})
</div>
<div class="form-group">
<label for="activo">Activo:</label>
@Html.TextBoxFor(m => m.Activo, new { @activo= "activo", @class = "form-control" })
</div>
<div class="container-fluid">
<div class="col-md-12 text-right">
<input type="submit" value="Guardar" class="btn btn-primary" />
</div>
</div>
}
控制器(更新方法有“id”作为参数,我不能像参数那样使用对象)
public ActionResult Detail(Peticion peticion)
{
if (ModelState.IsValid)
{
var id = peticion.Id;
_peticionService.Update(id);
return RedirectToAction("Index");
}
return View();
}
Class PeticionService
public bool Update(int id)
{
if (id > 0)
{
var peticionOld = _peticiones.FirstOrDefault(u => u.Id == id);
if (peticionOld != null)
{
//How to update item list??
return true;
}
}
return false;
}
如何使用id?
更新“PeticionService”类中的列表答案 0 :(得分:0)
我会像下面那样处理你的问题。
为您的视图创建视图模型。
public class PeticoneViewModel
{
public Peticione CurrentPeticione { get; set; }
}
然后有一个服务来处理对列表源的检索和更新。
public class PeticoneService
{
public Peticione GetPeticioneByID(int id)
{
//Put your implementation here.
return new Peticione();
}
public bool SavePeticioneByID(int id, string newValue)
{
//Put your implementation here.
return true;
}
}
然后创建一个控制器以返回详细信息视图并处理更新
public class PeticioneController : Controller
{
public ActionResult Detail(int peticonID)
{
var peticoneService = new PeticoneService();
var peticoneViewModel = new PeticoneViewModel();
peticoneViewModel.CurrentPeticione = peticoneService.GetPeticioneByID(peticonID);
return View("Detail",peticoneViewModel);
}
public bool UpdatePeticone(int id, string newValue)
{
if (id > 0)
{
var peticoneService = new PeticoneService();
return peticoneService.SavePeticioneByID(id, newValue);
}
return false;
}
}
同样在理想的世界中,您的服务应该注入控制器,因此控制器不负责服务实例化。但这是另一个问题。
希望以上有所帮助。