Binding an ASP.NET Model to ProfileCommon

I am wondering if there is a good example of how to edit ASP.NET profile settings in MVC using model binding.

I currently have:

  • a custom ProfileCommon class derived from ProfileBase.
  • strongly typed view (such as ProfileCommon)
  • Receive and publish actions on the controller that work with ProfileCommon and the corresponding view. (see code below).

Viewing profile information works - the form displays all the fields that are correctly filled.

Saving the form, however, gives an exception: System.Configuration.SettingsPropertyNotFoundException: the 'FullName' parameter property was not found.

Thinking about this makes sense, since the model binding will create an instance of the ProfileCommon class, and not grab one of the httpcontext. Also, saving is probably redundant, as I think the profile automatically saves itself when it changes - in this case, perhaps even if the verification fails. Correctly?

In any case, my current thought is that I probably need to create a separate Profile class to bind to the model, but it seems a little redundant when I already have a very similar class.

Is there a good example for this somewhere?

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Edit()
    {
        return View(HttpContext.Profile);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(ProfileCommon p)
    {
        if (ModelState.IsValid)
        {
            p.Save();
            return RedirectToAction("Index", "Home");
        }
        else
        {
            return View(p);
        }
    }
+3
source share
1 answer

, , ProfileCommon ( HttpContext) - - , DefaultModelBinder: , .

, , IModelBinder, :

public class ProfileBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        return controllerContext.HttpContext.Profile;
    }
}

, .

ProfileBinder, Edit :

public ActionResult Edit([ModelBinder(typeof(ProfileBinder))] ProfileCommon p)
+3

Source: https://habr.com/ru/post/1716653/


All Articles