如何preserve /保护ASP.NET MVC中编辑某些领域 [英] How to Preserve/Protect Certain Fields in Edit in ASP.NET MVC

查看:96
本文介绍了如何preserve /保护ASP.NET MVC中编辑某些领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC中的编辑操作,某些领域可以从HiddenFieldFor用户隐藏。然而,这并不能保护领域(如身份证,数据创建日期)进行编辑。

In an Edit action in ASP.NET MVC, certain fields can be hidden from user with HiddenFieldFor. However this doesn't protect the fields (such as ID, data creation date) from being edited.

例如,一个模范学生有场号,姓名和生日。我想允许用户更新名称,而不是ID,也没有生日。

For example, a model Student has fields Id, Name and Birthday. I like to allow users to update the Name, but not Id nor Birthday.

对于编辑动作像这样

public ActionResult Edit(Student student)
{
    if (ModelState.IsValid)
    {
        db.Entry(student).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(student);
}

我如何prevent编号和生日被编辑?谢谢!

How can I prevent Id and Birthday from being edited? Thanks!

推荐答案

您应该使用其中只包含要编辑的属性视图模型:

You should use a view model which contains only the properties that you want to be edited:

public class EditStudentViewModel
{
    public string Name { get; set; }
}

和则:

public ActionResult Edit(StudentViewModel student)
{
    ...
}

其中的另一种方法,我不建议是从结合排除某些属性:

Another technique which I don't recommend is to exclude certain properties from binding:

public ActionResult Edit([Bind(Exclude = "Id,Birthday")]Student student)
{
    ...
}

或包括:

public ActionResult Edit([Bind(Include = "Name")]Student student)
{
    ...
}

这篇关于如何preserve /保护ASP.NET MVC中编辑某些领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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