2

I have really strange problem. So, my structure is like this

<div id="tasks">
   @Html.Partial("_Tasks", tasks)
</div>

and in _Tasks I do a foreach through all tasks and for each task I have additional partial

...
@Html.Partial("_Time", new TimeViewModel(task))
...

and inside of _Time I have form

...
@Html.TextBoxFor(m => m.Name)
....

So in a view I render a partial and then inside again multiple partials and inside it a form. When I perform a page load, it works. Problem begins with when I'm using ajax, so I perform edit to Time and post to server and update #tasks with returned html.

I'm my controller action I have...

...
return View("_Tasks", tasks);

and the problem now is that all inputs generated by @Html.TextBoxFor(m => m.Name) have the same value. Why? If I do

@Html.DisplayFor(m => m.Name)

I works just fine. I also tried with

@Html.TextBoxFor(m => m.Name, new { Value = Model.Name })

and it works, but it looks hackish to me.

The question is, why is get this behavior? Why does all TextBoxFor have same value?

FrEaKmAn
  • 1,785
  • 1
  • 21
  • 47

1 Answers1

1

Default model binder in ASP.NET MVC determines how to map the values to your model by using name attributes on input tags. All the html helpers generate markup with that in mind.

So when you write

@Html.TextBoxFor(m => m.Name)

It generates something like this:

<input type="text" name="Name" />

However when you use this helper in a partial view and try to bind a model that's a property of the main model, it won't work. Html helper in the partial will still generate markup thinking its model is the main model. So your input will be binded to main model's Name property. You can take a look a this question for solving this problem. Also keep in mind the default binder can not pick up complex collections when you handle post requests.

Community
  • 1
  • 1
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156