How to save / protect certain fields in an editor in ASP.NET MVC

In the Edit action in ASP.NET MVC, certain fields can be hidden from the user using HiddenFieldFor. However, this does not protect the fields (such as ID, data creation date) from editing.

For example, the Student model has Id, Name, and Birthday fields. I like to let users update the name, but not the id and birthday.

For an editing action like this

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

How can I disable editing Id and Birthday? Thank!

+5
source share
2 answers

You should use a view model that contains only those properties that you want to edit:

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

and then:

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

, , :

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

:

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

, , , . ActionLink .

:

[Bind(Include = "Name")]
public class Student
{
    int Id { get; set; }
    int Name { get; set; }
    DateTime Birthday { get; set; }
}

, , , .

, , - , :

public class ModelExpression<T>
{
    public string GetExpressionText<TResult>(Expression<Func<T, TResult>> expression)
    {
        return ExpressionHelper.GetExpressionText(expression);
    }
}

public class Student
{
    public static string[] EditBinding = GetEditBinding().ToArray();

    int Id { get; set; }
    int Name { get; set; }
    DateTime Birthday { get; set; }

    static IEnumerable<string> GetEditBinding()
    {
        ModelExpression<Student> modelExpression = new ModelExpression<Student>();
        yield return modelExpression.GetExpressionText(s => s.Name);
    }
}

, TryUpdateModel .

+1

All Articles