简体   繁体   中英

How to set value of hidden field in mvc 5 view based on the onchange event of a control that is in an index

So I have a list inside a model like this:

public class model
{
    public string value1 {get;set;}
    public string value2 {get;set;}
    public List<subModel> value3 {get;set;}
}

public class subModel
{
    public string value4 {get;set;}
    public string value5 {get;set;}
    public bool dirtyFlag {get;set;}
}

In my view, I am able to display this model like this:

@for (int i = 0; i < Model.subModel.Count; i++ )
{
    @Html.DropDownListFor(model => model.subModel[i].value4, Model.value4Lookup, 
          Model.subModel[i].value4, new { onchange = "MarkRecordDirty()" })
}

I want to be able to use the onchange event of the drop down list to set the dirtyFlag to true, but I'm not sure how to pass the value of [i] in Model.subModel[i].value4 to the javascript function MarkDirtyRecord()

Any Ideas? Thanks

Well, if all you need to do is pass the value of i to the client-side code, you can do that with string concatenation:

onchange = "MarkRecordDirty(" + i.ToString() + ")"

Each iteration of the loop creates new output, so the resulting tags would have different outputs:

... onchange="MarkRecordDirty(0)" ...
... onchange="MarkRecordDirty(1)" ...
... onchange="MarkRecordDirty(2)" ...
... onchange="MarkRecordDirty(3)" ...
etc.

As for the exact question asked, that should do the trick. However, I suspect that there could be more to the issue at hand. At the very least this is going to make the code fairly brittle with an assumed dependency on ordering of records. That might not cause any problems, but then again it might. I can't know without knowing more about the overall solution you're building.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM