在MVC4中创建和编辑的相同视图 [英] Same view for both create and edit in MVC4

查看:52
本文介绍了在MVC4中创建和编辑的相同视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以为创建和编辑操作使用单个剃刀视图吗?

Can we have a single razor view for both Create and Edit operations?

如果是,我们如何实现这一目标?

If yes, how do we achieve this?

推荐答案

可以.

发布后,检查控制器的主键值是否为0,然后插入,否则为Update.

On post, check in your controller whether the primary key has value 0 then Insert, otherwise Update.

对于创建"和编辑",视图应相同.

View should be the same for Create and Edit.

只记得包括:

@Html.HiddenFor(model=>model.ID)

您认为

例如:

型号:

public class DescriptionModel
{
    [Key]
    public int ID { get; set; }

    public string Description { get; set; }
}

CreateEdit.cshtml:

CreateEdit.cshtml:

@model DescriptionModel

@using (Html.BeginForm("CreateEdit"))
{
    @Html.HiddenFor(model=> model.ID)
    @Html.EditorFor(model=> model.Description)
    <input type="submit" value='Submit' />
}

DescriptionModel控制器:

DescriptionModel controller:

public ActionResult Create()
{
    return View("CreateEdit", new DescriptionModel());
}
public ActionResult Edit(int id)
{
    return View("CreateEdit", db.DescriptionModels.Find(id));
}

// Submit and add or update database
[HttpPost]
public ActionResult CreateEdit(DescriptionModel model)
{
    if (ModelState.IsValid)
    {
       // No id so we add it to database
       if (model.ID <= 0)
       {
           db.DescriptionModels.Add(model);
       }
       // Has Id, therefore it's in database so we update
       else
       {
           db.Entry(model).State = EntityState.Modified;
       }
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(model);
}

这篇关于在MVC4中创建和编辑的相同视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆