开发者

FormCollection modify keys

开发者 https://www.devze.com 2023-03-28 16:45 出处:网络
How can I override keys in FormCollection (I need this because I have a property bound to multiple CheckBoxes in a View)? I did try this when a post back is in Action:

How can I override keys in FormCollection (I need this because I have a property bound to multiple CheckBoxes in a View)? I did try this when a post back is in Action:

formCollection["DecisionReasons"] = formCollection["开发者_开发知识库DecisionReasons"].Replace(",false", "").Replace("false,", "").Replace(",","|");

...but when I UpdateModel only the first value is updated in the model (in my model I have a DecisionReason string).

Do I need a ModelBinder (how can I do that?) or is there another way to do this?


Part of View

<div style="width:300px;height:250px;overflow:auto;">
@foreach (var a in (IEnumerable<SelectListItem>)ViewBag.AllDecisionReasons)
{
    @Html.CheckBox("DecisionReasons", a.Selected, new { value = a.Value })

    <label>@a.Text</label><br />
}
@Html.ValidationMessage("DecisionReasons", (string)Model.DecisionReasons)

if i check more than one checkbox in my View my Model property wich is string is updated with only one value example (if in View i check 2 checkboxes my Model will be updated with first value, so i need that Model property have value "valu1,valu2" and so on.)

sorry for my bad english.


I commented, above, asking for more details, but I get the impression that you're using checkboxes to represent the individual values in a Flags enumeration.

The default model binder doesn't handle mapping flags in this way, but I found a custom model binder that does in this article.

Edit:

OK, I see from your update (which would be better if you added it to your question, rather than posting it as an answer), your model has a comma-delimited string property containing each of the selected DecisionReasons.

I suggest that you consider the use of a ViewModel. The ViewModel is an abstraction of your model that is tailored for the way in which you present it in your view.

You can derive your ViewModel from your Model class, to reduce the amount of work. Consider this (untested) code:

public class MyModel
{
    public virtual string DecisionReasons { get; set; }
}

public class MyViewModel : MyModel
{
    public string[] DecisionReasonValues { get; set; }

    public override string DecisionReasons
    {
        get
        {
            return string.Join(",", DecisionReasonValues);
        }
        set
        {
            DecisionReasonValues = value.Split(',');
        }
    }
}

Use MyViewModel as the model for your View and use DecisionReasonValues to render the checkboxes, not DecisionReasons. ASP.NET MVC will populate DecisionReasonValues from your checkboxes but you can access them as a comma-delimeted string through the overridden DecisionReasons property.

0

精彩评论

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