两个相同的观点创建和编辑+ MVC4 [英] Same view for both create and edit + MVC4

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

问题描述

我们能有一个单一的Razor视图为创建编辑操作?

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

如果有,可以请你告诉我们如何才能做到这一点?

If yes, can you please show how we can achieve this?

推荐答案

当然可以。

在后,请检查您的控制器中的主键是否有值0,则插入,否则更新。

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天全站免登陆