How to Preserve/Protect Certain Fields in Edit in ASP.NET MVC

后端 未结 2 1055
盖世英雄少女心
盖世英雄少女心 2020-12-19 11:22

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

相关标签:
2条回答
  • 2020-12-19 11:38

    I assume you have to have the properties in your Model so that in View you can use them to render useful information e.g. an ActionLink with ID or some readonly Text.

    In this case you can define your model with an explicit binding:

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

    This way when updating your model, if the user submits an extra Id it will not be bound.

    Another idea I like is having your model know its bindings per scenario and have them compiler validated:

    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);
        }
    }
    

    This way in your Action when calling TryUpdateModel you can pass this information.

    0 讨论(0)
  • 2020-12-19 12:01

    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; }
    }
    

    and then:

    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)
    {
        ...
    }
    

    or include:

    public ActionResult Edit([Bind(Include = "Name")]Student student)
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题