Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call EditorFor from the controller

Tags:

c#

asp.net-mvc

I have list of locations

public class Location
{
    public string LocationName { get; set; }
    public string Address { get; set; }
}

I created editor template for this class

<div>
   <span>@Html.TextBoxFor(a => a.LocationName)</span>
   <span style="color: red;">@Html.TextBoxFor(a => a.Address )</span>
</div>

The problem is that locations load with ajax to my page and then I am going to send the results back to the server. But how to get this location with specific index? I mean that for the first location it will generate like this:

<input type="text" name="Locations[0].LocationName" />

For the second location when I press "Add Location" button it should get this location from the server (from action of controller as html string) but with index 1 not 0 because it is next location.

Is it possible to achieve it? Or I am doing something wrong?

like image 337
Sergey Avatar asked Jul 31 '13 12:07

Sergey


2 Answers

Something like this

    [HttpGet]
    public virtual ActionResult LocationEditor(int index)
    {
        ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("Locations[{0}]", index);
        return PartialView(@"EditorTemplateExplicitPathAsOnlyViewNameAintGonnaWork.cshtml");
    }

And for location names container

<div class="locations-container" data-item-count="@Model.Count">
    @for (int j = 0; j < Model.Count; j++)
    {
        @Html.EditorFor(model => model[j])
    }
    <a href="#" class="add-location">Add Location</a>
</div>

The rest of tiny bit of javascript to increment data-item-count upon adding and call LocationNameEditorLocationNameEditor action with new index is upon you.

like image 118
archil Avatar answered Sep 23 '22 12:09

archil


You could try using partial views and create an action method that returns an AjaxResult (I believe that's correct). Then you could have the controller populate the view model and pass it to the partial view that's to be rendered in your page at the place you specify.

like image 36
fourpastmidnight Avatar answered Sep 23 '22 12:09

fourpastmidnight