Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6001989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T00:54:48+00:00 2026-05-23T00:54:48+00:00

I created a view with a variable length list as described here: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ .

  • 0

I created a view with a variable length list as described here: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/.

I am trying to use the PRG pattern with action filters as described at point 13 here: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx.

I have an Edit action:

    [HttpGet, ImportModelStateFromTempData]
    public ActionResult Edit(int id)
    {
    }

And the post action:

    [HttpPost, ExportModelStateToTempData]
    public ActionResult Edit(int id, FormCollection formCollection)
    {
        if (!TryUpdateModel<CategoryEntity>(category, formCollection))
        {
            return RedirectToAction("Edit", new { id = id });
        }

        // succes, no problem processing this...
        return RedirectToAction("Edit", new { id = id });
    }

All works fine including validation and error messages.

The only problem I have is that newly added items and deleted items (client side deleted/added) are not preserved after the redirect. I am trying to find a way to update my model after the redirect with the new items. I changed the ImportModelStateFromTempData attribute to use the OnActionExecuting override instead of the OnActionExecuted override to have the ModelState available in the action but I don’t see a clean way to update my model from the passed in ModelState.

Changed ImportModelStateFromTempData:

public class ImportModelStateFromTempData : ModelStateTempDataTransfer
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;

        if (modelState != null)
        {
            filterContext.Controller.ViewData.ModelState.Merge(modelState);
        }
        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;

        //if (modelState != null)
        //{
        //    //Only Import if we are viewing
        //    if (filterContext.Result is ViewResult)
        //    {
        //        filterContext.Controller.ViewData.ModelState.Merge(modelState);
        //    }
        //    else
        //    {
        //        //Otherwise remove it.
        //        filterContext.Controller.TempData.Remove(Key);
        //    }
        //}
        base.OnActionExecuted(filterContext);
    }
}

Any input on this is much appreciated, thanks.

Harmen

UPDATE: Thought I might add some more of my (pseudo) code to make it more clear:

public class CategoryEntity
{
    public int Id;
    public string Name;
    public IEnumerable<CategoryLocEntity> Localized;
}

public class CategoryLocEntity
{
    public int CategoryId;
    public int LanguageId;
    public string LanguageName;
    public string Name;
}

My Edit view:

@model CategoryEntity

@{
    ViewBag.Title = Views.Category.Edit;
}

<h2>@Views.Category.Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript"><!--

    $(document).ready(function () {
        $('#addItem').click(function () {
            var languageId = $('#languageId').val();
            var index = $('#editor-rows').children().size() - 1;
            $.ajax({
                url: this.href + '?languageId=' + languageId + '&index=' + index,
                cache: false,
                error: function (xhr, status, error) {
                    alert(error);
                },
                success: function (html) {
                    $('#editor-rows').append(html);
                }
            });
            return false;
        });

        $("a.removeItem").live("click", function () {
            $(this).parents("div.editor-row:first").remove();
            return false;
        });
    });

--></script>

@using (Html.BeginForm()) 
{
    @Html.ValidationSummary(false)
    <fieldset>
        <legend>@Views.Shared.Category</legend>
        @Html.HiddenFor(model => model.Id)
        <div id="editor-rows">
            <div class="editor-row">
                <div class="editor-label">
                    @Html.LabelFor(model => model.Name, Views.Shared.NameEnglish)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.Name)
                    @Html.ValidationMessageFor(model => model.Name)
                </div>
            </div>

            @for (int i = 0; i < Model.Localized.Count; i++)
            {
                @Html.EditorFor(m => m.Localized[i], "_CategoryLoc", null, null)
            }
        </div>

        <div class="editor-label"></div>
        <div class="editor-field">
            @Html.DropDownList("languageId", (IEnumerable<SelectListItem>)ViewBag.LanguageSelectList)
            @Html.ActionLink(Views.Category.AddNewLanguage, "AddNewLanguage", null, new { id = "addItem" })
        </div>

        <p class="clear">
            <input type="submit" value="@Views.Shared.Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink(Views.Shared.BackToList, "Index")
</div>

Editor template for the CategoryLocEntity:

@model CategoryLocEntity

<div class="editor-row">
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.LanguageId)
    <div class="editor-label">
        @Html.LabelFor(model => model.LanguageName, Model.LanguageName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        <a href="#" class="removeItem">@Views.Shared.Remove</a>
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T00:54:49+00:00Added an answer on May 23, 2026 at 12:54 am

    I found a solution (probably not the most elegant one but it works for me). I created my own ModelStateValueProvider to be used with UpdateModel. The code is based on the DictionaryValueProvider. See http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System.Web/System/Web/Mvc/DictionaryValueProvider%601.cs.htm.

    public class ModelStateValueProvider : IValueProvider
    {
        HashSet<string> prefixes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        ModelStateDictionary modelStateDictionary;
    
        public ModelStateValueProvider(ModelStateDictionary modelStateDictionary)
        {
            if (modelStateDictionary == null)
                throw new ArgumentNullException("modelStateDictionary");
    
            this.modelStateDictionary = modelStateDictionary;
    
            FindPrefixes();
        }
    
        private void FindPrefixes()
        {
            if (modelStateDictionary.Count > 0)
                prefixes.Add(string.Empty);
    
            foreach (var modelState in modelStateDictionary)
                prefixes.UnionWith(GetPrefixes(modelState.Key));
        }
    
        public bool ContainsPrefix(string prefix)
        {
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
    
            return prefixes.Contains(prefix);
        }
    
        public ValueProviderResult GetValue(string key)
        {
            if (key == null)
                throw new ArgumentNullException("key");
    
            return modelStateDictionary.ContainsKey(key) ? modelStateDictionary[key].Value : null;
        }
    
        static IEnumerable<string> GetPrefixes(string key)
        {
            yield return key;
            for (int i = key.Length - 1; i >= 0; i--)
            {
                switch (key[i])
                {
                    case '.':
                    case '[':
                        yield return key.Substring(0, i);
                        break;
                }
            }
        }
    }
    
    public class ModelStateValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            return new ModelStateValueProvider(controllerContext.Controller.ViewData.ModelState);
        }
    }
    

    I use it in de Edit (Get) action like:

    [HttpGet, ImportModelStateFromTempData]
    public ActionResult Edit(int id)
    {
      var category = new CategoryEntity(id);
      if (!ModelState.IsValid)
      {    
         TryUpdateModel<CategoryEntity>(category, 
             new ModelStateValueProviderFactory().GetValueProvider(ControllerContext));
      }
      return View(category);
    }
    

    Looking forward to your comments…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've followed Steve Sanderson’s Editing a variable length list, ASP.NET MVC 2-style guide and
I have created navigaton view using Sencha touch 2. Navigation view has list component
I am in the process of developing a lengthy list view that is created
I am following Steven Sanderson's blog post here to create an editable and variable
Here is the situation: I have created a custom view class with UITextView as
I have created View A and View B. My window has View A displayed
I created a view that has a distinct in the select clause. When I
I have created a view for a table as: CREATE VIEW anonymous_table AS SELECT
So I've created a view controller that creates a custom view that, if it
I've created a view on 3 tables in my database, they are as follows:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.