开发者

Detect that a hidden form field has changed?

开发者 https://www.devze.com 2023-04-08 03:49 出处:网络
I am using 开发者_JAVA百科a hidden form field to store the current record that an user is editing. How can I prevent the user from changing that field? Would MVC3\'s anti-forgery helpers work, or do I

I am using 开发者_JAVA百科a hidden form field to store the current record that an user is editing. How can I prevent the user from changing that field? Would MVC3's anti-forgery helpers work, or do I need to roll my own checks?


Rather than trying to check if the user changed anything, you should check that they are permitted to edit what ever record is indicated by the ID submitted.

If they are allowed to edit the ID in question, let them do it. If not, don't. Don't even bother worrying about whether they have changed the form data, which is trivial to do.

Antiforgery tokens don't really serve any purpose then, btw.


See How to detect if form field has changed without using hidden field

Suggestions there are to use a hash and compare on postback to check if changes have been made.


Edit

Seems I misunterstood your question, sorry. Indeed, AntiForgeryToken won't help you prevent that. You can either store these non-editable informations in your Model (in my example the Account class) without exposing it or in your Session. You can also put some checking/event-raising in your model's properties to detect unwanted edition.

Old-misunterstood-answer

You can use the HtmlHelper method HtmlHelper.AntiForgeryToken

1/In your form:

@using (Html.BeginForm("Edit", "User", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Account</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        //Your other fields

        <p>
            @Html.AntiForgeryToken()
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

2/ In your Post action method:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Models.Account account)

Take note that AntiForgeryToken only works with POST request and that cookies must be (obviously) enabled :).


For prevent CSRF attacks, you can use Html.AntiForgeryToken helper method in your form section

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号