I'm trying to load a partial view using JavaScript, in turn the partial view will have a View Bag", to loop through.
All is working well, until I try to render the partial view I get an "object Object" error, if I remove the View bag loop the partial view loads
Controller
[HttpPost]
public ActionResult ServiceDetails(int id )
{
int count = 0;
var m = from c in db.ServiceCategoryFields
where c.serviceTypeID == id
select c;
ViewBag.count = count;
ViewBag.m = m.ToList();
return PartialView(m.ToList());
}
Partial View
<table style ="width:100% ">
<tr>
#foreach (var image in (List<String>)ViewBag.m)
{
<td>
#image
</td>
}
</tr>
JS File
type: "POST",
success: function (data) {
display.html('');
display.html(data);
},
error: function (reponse) {
alert("JS Error : " + reponse.toString());
}
Quick Solution
Based on your controller code below
[HttpPost]
public ActionResult ServiceDetails(int id )
{
int count = 0;
var m = from c in db.ServiceCategoryFields
where c.serviceTypeID == id
select c;
ViewBag.count = count;
ViewBag.m = m.ToList();
return PartialView(m.ToList());
}
ViewBag.m would be an instance of List<ServiceCategoryField>, but you convert it to List<string> in the partial view
#foreach (var image in (List<String>)ViewBag.m)
so you got the error. Assuming that PropertyName is the property of ServiceCategoryField with the value that you want to display inside <td> tags, you need to convert ViewBag.m to List<ServiceCategoryField> in the partial view as below
<table style ="width:100% ">
<tr>
#foreach (var image in (List<ServiceCategoryField>)ViewBag.m)
{
<td>
#image.PropertyName
</td>
}
</tr>
Alternative Solution
The previous solution requires converting ViewBag.m and it could produce runtime errors if you convert ViewBag.m to the wrong type. You can avoid the conversion in the partial view by using this alternative solution.
The first thing to do is creating a model class that will be used by the partial view, let's say the class name is ServiceDetailsViewModel and it has Count and Images property
public class ServiceDetailsViewModel
{
public int Count { get; set; }
public List<string> Images { get; set; }
}
Create an instance of ServiceDetailsViewModel, assign the properties, and pass model to the partial view in the controller. I assume PropertyName is a string and c.PropertyName is where the image in the partial view comes from
[HttpPost]
public ActionResult ServiceDetails(int id )
{
int count = 0;
var m = from c in db.ServiceCategoryFields
where c.serviceTypeID == id
select c.PropertyName;
ServiceDetailsViewModel model = new ServiceDetailsViewModel();
model.Count = count;
model.Images = m.ToList();
return PartialView(model);
}
Set ServiceDetailsViewModel as the model by using the below syntax at the top of your partial view code
#model ServiceDetailsViewModel
and loop through Model.Images as below
<table style ="width:100% ">
<tr>
#foreach (var image in Model.Images)
{
<td>
#image
</td>
}
</tr>
Related
I have a table containing a list of games. Each row contains a game ID, a drop-down list containing all the versions of the game and a status which currently shows the status of the latest version.
I want to update a single row on the table based on what the version drop-down list value contains which should change the value of the status cell.
This change should also change the ActiveVersion field in the view model.
I think this is achievable by using AJAX, model binding and potentially partial views but I'm unsure on how to do it.
I have attempted to simplify my problem by using versioning of games with strings and integers as data types as an example as I am using complex models and viewmodels in my webapp.
I have an MVC view as follows
#model IEnumerable<GameViewModel>
...
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => #item.Versions.Where(x => x.Version == item.ActiveVersion).FirstOrDefault().Status)
</td>
<td>
<select asp-for="#item.ActiveVersion" asp-items="#item.VersionsList"></select>
</td>
</tr>
}
</tbody>
My view model is as follows
public class GameViewModel
{
public string Id { get; set; }
public List<GameVersion> Versions { get; set; }
public string ActiveVersion { get; set; }
//Constructor - initialises active version to highest version
public GameViewModel(Game game)
{
Id = game.Id;
Versions = game.Versions;
ActiveVersion = game.Versions.Max(x => x.Version).ToString();
}
//Returns a list of all versions to be used in dropdown
public List<SelectListItem> VersionsList
{
get
{
List<SelectListItem> versionList = new List<SelectListItem>();
foreach (GameVersion gv in Versions)
{
versionList.Add(new SelectListItem { Value = gv.Version.ToString(), Text = gv.Version.ToString() });
}
return versionList;
}
}
}
My models are as follows
public class GameVersion
{
public int Version { get; set; }
public string Status { get; set; }
}
public class Game
{
public string Id { get; set; }
public List<GameVersion> Versions { get; set; }
}
I am using ASP.NET Core 3.1 to develop a MVC webapp.
You can use jQuery to control the implementation of the drop-down list to dynamically update the value of the state, according to the model you provide.
Here is a working demo like below:
Model:
public class GameVersion
{
public int Version { get; set; }
public string Status { get; set; }
}
public class Game
{
public string Id { get; set; }
public List<GameVersion> Versions { get; set; }
}
public class GameViewModel
{
public string Id { get; set; }
public List<GameVersion> Versions { get; set; }
public string ActiveVersion { get; set; }
//Constructor - initialises active version to highest version
public GameViewModel(Game game)
{
Id = game.Id;
Versions = game.Versions;
ActiveVersion = game.Versions.Max(x => x.Version).ToString();
}
//Returns a list of all versions to be used in dropdown
public List<SelectListItem> VersionsList
{
get
{
List<SelectListItem> versionList = new List<SelectListItem>();
foreach (GameVersion gv in Versions)
{
versionList.Add(new SelectListItem { Value = gv.Version.ToString(), Text = gv.Version.ToString() });
}
return versionList;
}
}
}
View(Index.cshtml):
#model IEnumerable<GameViewModel>
<table>
<tbody>
#foreach (var item in Model)
{
<tr id="#item.Id">
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
<span>
#*change this line*#
#Html.DisplayFor(modelItem => #item.Versions.Where(x => x.Version.ToString() == item.ActiveVersion).FirstOrDefault().Status)
</span>
</td>
<td>
<select class="activeVersion_#item.Id" asp-for="#item.ActiveVersion" asp-items="#item.VersionsList"></select>
</td>
</tr>
}
</tbody>
</table>
#section Scripts{
<script>
$(function () {
var gameModel =#Json.Serialize(Model);
$('*[class^="activeVersion"]').change(function () {
var vers = $(this).find('option:selected').val()
console.log(vers)
var stat = $(this).parent().prev().find('span');
stat.empty();
var nodeid = $(this).attr('class').split('_')[1]
$.each(gameModel, function (index, game) {
if (nodeid == game['id']) {
console.log(game['versions'])
$.each(game['versions'], function (indx, version) {
if (vers == version['version'])
stat.text(version['status'])
})
}
})
})
})
</script>
}
Controller(For easy testing,I set the value manually):
public IActionResult Index()
{
var games = new Game
{
Id = "game",
Versions = new List<GameVersion> {
new GameVersion{ Version=1,Status="Status1"},
new GameVersion{ Version=2,Status="Status2"},
new GameVersion{ Version=3,Status="Status3"},
},
};
var games2 = new Game
{
Id = "game2",
Versions = new List<GameVersion> {
new GameVersion{ Version=4,Status="Status4"},
new GameVersion{ Version=5,Status="Status5"},
new GameVersion{ Version=6,Status="Status6"},
},
};
var gameviewModels = new List<GameViewModel> {
new GameViewModel(games),
new GameViewModel(games2)
};
return View(gameviewModels);
}
Result:
There are a number of ways to achieve this.
A simple one that doe snot require Ajax is to wrap each select within a form tag which posts to an action that takes an ID and VERSION. Within this form add a hidden field for the ID.
Add an OnChange event to the select and use javascript to post back the form.
At the action, perform your update and redirect back to your index action that displays the list
If you want to use ajax then create a javascript method passes your select control as a parameter instead of posting back. From this parameter you can get the select value. You can get the previous control (the hidden ID input) to get that value then pass these back to your action.
Your action can pass back a JSON result of OK or an error or even the table cell html. Assuming success, either with HTML passed back by the action (you can use a partial view which replaces the original table cell content) or already knowing having the correct select action already displayed then you are done. If there is an error you have to decide to show that message and whether to put the select back to the original value
I have this ViewModel which incorporates 3 other viewmodels and a list:
public class GroupPageViewModel{
public string GroupName { get; set; }
public GroupSelectViewModel _groupSelectVM {get; set;}
public List<User> _users { get; set; }
public ViewModelStudent _studentVM { get; set; }
public ViewModelGroupMembers _groupMembersVM { get; set; }
}
In the view I can access each of these sub-ViewModels by Model._groupSelectVM, each of the sub-ViewModels are associated with a partial view. The problem arises when I need to refresh just one or two partial views, I'm not sure how to access the inner ViewModels returned in an Ajax success, and as I'm relatively new to MVC and asp.net in general. And I literally know next to nothing about JavaScript, jquery or Ajax.
How would I go about getting a specific ViewModel from the main ViewModel in an Ajax success?
This is just one example for the clarification requested all the others are pretty much the same (although some of them might need to update mutliple partial views -
From the controller:
[HttpPost]
public ActionResult Index(string groupChoice = "0", string newGroup = "")
{
string groupName = "";
if (groupChoice == "0" && newGroup != "")
{
if (ModelState.IsValid)
{
Group group = new Group
{
GroupName = newGroup,
Active = true
};
db.Groups.Add(group);
db.SaveChanges();
PopulateLists();
}
}
else if (groupList == null)
{
groupList = (List<SelectListItem>)Session["groupList"];
Session["groupName"] = groupName = groupList.Where(m => m.Value == groupChoice).FirstOrDefault().Text;
MembersInSpecificGroup(groupName, groupMembers, groupMembersList);
groupPageVM._groupMembersVM = groupMembers;
}
return View("GroupSelection", groupPageVM);
}
The script:
$(document).ready(function () {
$('#selectedGroup').change(function () {
var data = {
groupChoice: $('#selectedGroup').val()
};
var groupChoice = $('#selectedGroup').val();
$.ajax({
url: '/Group/Index/',
type: 'POST',
data: { groupChoice: groupChoice },
success: function (data) {
setTimeout(function () {
delayGroupSuccess(data);
}, delay);
}
});
})
});
function delayGroupSuccess(data) {
$("#groupSelect").html(data);
}
The main page:
#model EMBAProgram.ViewModels.GroupPageViewModel
#{ Layout = "~/Views/Shared/_Layout.cshtml"; }
<h2>Group Selection</h2>
<div class="row" id="groupSelect">
#{ Html.RenderPartial("_GroupSelect", Model._groupSelectVM);}
</div>
<hr size="5" />
<div style="display: flex;">
<div>
#{Html.RenderPartial("_Students", Model._studentVM);}
</div>
<div>
#{ Html.RenderPartial("_GroupMembers", Model._groupMembersVM);}
</div>
<div>
#{ Html.RenderPartial("_Users", Model._users);}
</div>
<br style="clear: left;" />
</div>
The partial view:
#model EMBAProgram.ViewModels.ViewModelGroupMembers
<div class="table-responsive" id="groupResults">
<table class="table table-condensed table-responsive">
<thead>
<tr>
<th>#Html.DisplayName("M-Number")</th>
<th>#Html.DisplayName("Name")</th>
<th>#Html.DisplayName("Student")</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model._groupVM) {
<tr>
<td>#Html.DisplayFor(m => item.MNumber)</td>
<td>#Html.DisplayFor(m => item.Name)</td>
<td>#Html.DisplayFor(m => item.Student)</td>
</tr>
}
</tbody>
</table>
</div>
Basically I need to be able pull the ViewModel for the partial view from the main ViewModel (which I believe is what is being returned in the Ajax,) and refresh the partial view.
I removed the original answer, it's available in the edit log if folks want to see it I think. But it was taking up too much space and was incorrect.
You can return multiple partial views, I thought it was a built in way to get them to a string (I was in a rush in my comment), but I've got a working example.
In the controller I have the following:
public ActionResult Index()
{
var model = new TestViewModel
{
Students = GetStudents(),
Categories = GetCategories(),
Groups = GetGroups()
};
return View("Index", model);
}
// Returns multiple partial views as strings.
public ActionResult StudentsAndGroups()
{
return Json(new
{
Students = RenderRazorViewToString("_Students", GetStudents()),
Groups = RenderRazorViewToString("_Groups", GetGroups())
}, JsonRequestBehavior.AllowGet);
}
// Creates a string from a Partial View render.
private string RenderRazorViewToString(string viewName, object model)
{
ControllerContext.Controller.ViewData.Model = model;
using (var stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
I have my main index view that looks like the following:
<button class="refresh">Refresh</button>
<div class="row">
<div class="col-md-4 students">
#{
Html.RenderPartial("_Students", Model.Students);
}
</div>
<div class="col-md-4">
#{
Html.RenderPartial("_Category", Model.Categories);
}
</div>
<div class="col-md-4 groups">
#{
Html.RenderPartial("_Groups", Model.Groups);
}
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(".refresh").click(function () {
$.get("/Home/StudentsAndGroups", function (d) {
$(".students").html(d.Students);
$(".groups").html(d.Groups);
})
});
</script>
}
The controller action StudentsAndGroups turns two partial views into strings. From there, the javascript calls that view and accesses the elements and returns them.
Helper method for rendering a view as a string was found here: https://stackoverflow.com/a/34968687/6509508
I created a ASP.Net MVC 5 project and used Knockout.js library.
I have a View called Statement which basically shows the a table with a couple of Transaction items.
My complete Statement.cshtml is as follow:
#using Newtonsoft.Json;
#model IEnumerable<ATMMVCLearning.Models.Transaction>
#{
ViewBag.Title = "Statement";
}
<h2>Statement</h2>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td><strong>Transaction ID</strong></td>
<td><strong>Amount</strong></td>
</tr>
</thead>
<tbody data-bind="foreach:currentTransactions">
<tr>
<td data-bind="text:Id"></td>
<td data-bind="text:formattedPrice"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<span data-bind="click:previousPage" class="glyphicon glyphicon-circle-arrow-left"
style="cursor:pointer;"></span>
<span data-bind="text:currentPage"></span>
<span data-bind="click:nextPage"class="glyphicon glyphicon-circle-arrow-right"
style="cursor:pointer;"></span>
</td>
</tr>
</tfoot>
</table>
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script>
function formattedPrice(amount) {
var price = amount.toFixed(2);
return price;
}
function StatementViewModel() {
var self = this;
//properties
//note that there is a ko.observableArray for making bindings for array
self.transactions = #Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore}));
//TODO: embed transactions from server as JSON array
self.pageSize = 5; //number of transactions to display per page
self.currentPage = ko.observable(1); //the first observable. If the page changes, then the grid changes
self.currentTransactions = ko.computed(function () {
var startIndex = (self.currentPage() - 1) * self.pageSize; //because currentPage is an observable, we get the value by calling it like a function
var endIndex = startIndex + self.pageSize;
return self.transactions.slice(startIndex, endIndex);
});
//methods to move the page forward and backward
self.nextPage = function () {
self.currentPage(self.currentPage() + 1);
};
self.previousPage = function () {
self.currentPage(self.currentPage() - 1);
};
};
ko.applyBindings(new StatementViewModel()); //note this apply bindings, used extensively in KnockOut
</script>
As you can see in the <tbody> I have two <td> elements which have data-bind attribute:
<tbody data-bind="foreach:currentTransactions">
<tr>
<td data-bind="text:Id"></td>
<td data-bind="text:formattedPrice"></td>
</tr>
</tbody>
And the formattedPrice can be referred to the script section below:
function formattedPrice(amount) {
var price = amount.toFixed(2);
return price;
}
Now, I expect the resulting View when it is rendered should show a table with 5 transactions each page, where each table row shows an Id as well as its transaction amount. I.e. something like:
1 100.00
2 150.00
3 -40.00
4 111.11
5 787.33
However, when I render the page, I got the following result:
Instead of Id and amount, I got Id and javascript.
Any idea?
Update:
The Transaction class is as follow:
public class Transaction {
public int Id { get; set; } //this is internally used, not need to have anything
[Required]
[DataType(DataType.Currency)]
public decimal Amount { get; set; }
[Required]
public int CheckingAccountId{ get; set; }
public virtual CheckingAccount CheckingAccount { get; set; } //this is to force the entity framework to recognize this as a foreign key
}
Since formattedPrice is not part of your view-model, Knockout won't automatically unwrap it, nor will it pass it the amount argument.
Try this instead:
<td data-bind="text: formattedPrice(Amount)"></td>
Price probably needs to be computed field and you need to bind to price (I think). It's been a while since I did Knockoutjs.
I have a MVC project using Kendo controls. On one of the views is a drop down box and text box. Both are initially getting their values from the model. How can I change the model (and therefore the text box) when the user selects an item from the drop down?
For example, the Model is filled in the controller setting the original value of the item the drop down box is based on to "General" and the item the text box is based on to "Widgets". When the user selects "Special" from the drop down, the controller would query the database to get data based on "Special", find that the new value of the text box should say "Doodads", add "Doodads to the model and change the text box to "Doodads".
View
#model GPC.Models.ModelInstrumentListingDetail
#using (Html.BeginForm("InstrumentListingDetailClick", "Home", FormMethod.Post, new { id = "InstrumentListingDetailForm" }))
{
<div id="divInstrumentListingDetailHeader" class="detailDivs">
<table>
<tr>
<tr>
<td style="text-align: right;" class="dropdowns">
<label>Category:</label>
</td>
</tr>
</table>
</div> // divInstrumentListingDetailHeader
<div id="divInstrumentListingDetailBody" class="detailDivs details">
<table class="details">
#*Field 1*#
<tr>
<td style="text-align: right;">
#Html.DisplayFor(m => m.Label1)
</td>
<td width="2px;"> </td>
<td class="dropdowns">
#Html.TextBoxFor(m => m.Field1, new { #class = "details" })
</td>
</tr>
</table>
</div> // divInstrumentListingDetailBody
}
<script>
function onChange_ddInstrumentCategory(arg) {
var categoryID = $(arg).find('option:selected').val();
// Update model based on the category ID
}
</script>
Controller
public ActionResult InstrumentListingEdit(TblInstrumentTag model)
{
TblInstrumentTag currentInstrumentTag = data.GetInstrumentTagByID(model.InstrumentTagID);
// Fill Category drop down
List<TblInstrumentFormCategory> categories = data.GetAllCategories();
// Create model
ModelInstrumentListingDetail detailModel = new ModelInstrumentListingDetail
{
InstrumentTagID = currentInstrumentTag.InstrumentTagID,
InstrumentCategory = categories.FirstOrDefault().InstrumentFormCategoryID,
Field1 = currentInstrumentTag.FormCategory1Value1,
Label1 = categories.FirstOrDefault().Label1 + ":",
ieInstrumentCategories = new SelectList(categories, "InstrumentFormCategoryID", "InstrumentFormCategoryName")
};
return View("InstrumentListingEdit", detailModel);
}
Model
public class ModelInstrumentListingDetail
{
// Drop down ID's
public int InstrumentTagID { get; set; }
public int InstrumentCategory { get; set; }
// Detail fields
public string Field1 { get; set; }
// Detail labels
public string Label1 { get; set; }
// Drop downs for add/edit page
public IEnumerable<SelectListItem> ieInstrumentCategories { get; set; }
}
What I'd like is to get from the javascript to something like this code below to update the text box. I'd rather not post the entire page. I don't want the screen to "blink"; I just want the user to select an item from the dropdown and for the textbox value to change.
Need to get from jQuery to something like this without submitting the form:
public ActionResult UpdateModel(TblInstrumentTag model, int newCatgoryID)
{
TblInstrumentTag currentInstrumentTag = data.GetInstrumentTagByID(model.InstrumentTagID);
// Fill Category drop down
List<TblInstrumentFormCategory> categories = data.GetAllCategories();
// Create model
ModelInstrumentListingDetail detailModel = new ModelInstrumentListingDetail
{
InstrumentTagID = currentInstrumentTag.InstrumentTagID,
InstrumentCategory = categories.FirstOrDefault().InstrumentFormCategoryID,
Field1 = currentInstrumentTag.FormCategory2Value1, // <- Value of Field 1 has changed
Label1 = categories.FirstOrDefault().Label1 + ":",
ieInstrumentCategories = new SelectList(categories, "InstrumentFormCategoryID", "InstrumentFormCategoryName")
};
return View("InstrumentListingEdit", detailModel);
}
JQuery is a good place to start. If I understand correctly, you only want to query the DB after changing the drop down's value, and then changing the value of the textbox to the corresponding change.
JQuery:
$(document).ready(function(){
$('#myDropDown').change(selectionChange());
});
function selectionChange() {
var dropDownValue = $('#myDropDown').val();
var textBox = $('#myTextBox');
$.ajax({
url: "/mycontroller/querydb",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(dropDownValue),
success: function (data, status) {
textBox.val(data);
},
type: "post"
});
return;
}
Controller:
[HttpPost]
public JsonResult QueryDB(string dropDownValue)
{
string newTextBoxValue = string.Empty;
//your db code
return Json (newTextBoxValue) );
}
It's a fairly watered down version of a JQuery AJAX to MVC Controller deal. Hopefully it will work for you!
Here are my models
public class AddressBook
{
public string UserId { get; set; }
public IList<Address> Addresses { get; set; }
public AddressBook()
{
UserId = "";
Addresses = new List<Address>();
}
}
public class Address
{
public string Company { get; set; }
public string Title { get; set; }
public string FName { get; set; }
...
}
The controller builds the AddressBook with a list of addresses.
The main page uses the AddressBook model (#model mymodel.AddressBook) and I can access the different addresses using Model.Addresses[index].
On the page I display the list of addresses each with an Edit button (I stripped the html code off for clarity):
#model mymodel.AddressBook
...
#for (int i = 0; i < Model.Addresses.Count; i++)
{
#Model.Addresses[i].Company
#Model.Addresses[i].FName
...
#:<input type="image" src="/images/edit.gif" onclick="addressEdit('#i'); return false;" title="Edit" />
}
When the user clicks on the edit button I call javascript addressEdit and pass it the index of the selected address.
<script type="text/javascript">
function addressEdit(index) {
$('#FName').val('#Model.Addresses[index].FName');
$('#Addr1').val('#Model.Addresses[index].Company');
...
}
</script>
The problem is on the jQuery lines $('#FName').val('#Model.Addresses[index].FName'); Variable index is underlined in red in VS2012 with message "the name 'index' does not exist in the current context".
How do you pass the value on 'index' to extract the data I need?
Wrap your elements in a spans with some class name. Wrap everything in the loop a div too. I am also removing the onclick method from the markup because we will do it in the unobtrusive way.
#for (int i = 0; i < Model.Addresses.Count; i++)
{
<div class='entry'>
<span class='spanAddress'> #Model.Addresses[i].Company </span>
<span class='spanFName'> #Model.Addresses[i].FName </span>
<img src="/images/edit.gif" class='editLink' />
</div>
}
Now in your javascript
$(function(){
$(".editLink").click(function(e){
e.preventDefault();
var _this=$(this);
var fname=_this.closest("div.entry").find(".spanFName").html();
var add=_this.closest("div.entry").find(".spanAddress").html();
$('#FName').val(fname);
$('#Address').val(add);
});
});
Well, this is client side code remember. So the best place to look is what is generated client side. This means commenting out your javascript event and looking at what is actually rendered to get an idea of what is going on.
When you do that, you will see that the helper autogenerates the names and ids based on your models names. Keep in mind that the name attribute on the inputs is what allows for model binding on post.
So, with all of that in consideration, I would assume it would be something along these lines:
function addressEdit(index) {
$('#FName').val($("#Addresses_"+index+"__FName").val());
//..etc
}