how to bind more than one model with single view? - asp.net-mvc

Guys I have tried to use more than one Models with single view.
but I could not found the solution how to implement it.
I want to use One View data in Single past and the other in another part..
I have used the following code..
this is one view
#Html.Partial("Sidebar")
this is another view
<!-- start content -->
<div id="content">
<div class="post">
<h1 class="title">
Add New Post
</h1>
<p></p>
<div class="entry">
#using (Html.BeginForm())
{
<div>
<div style="display:inline;">
<div style="display: inline; float: left;">
#Html.Label("lblcategory", "Category", new { style = "Width:100px; float: left;" })
<div style="width: 150px; height: 60px; overflow-y: scroll; display: inline; float: left;">
#for (int i = 0; i < (int)TempData["Rows"]; i++)
{
for (int j = 0; j < (int)TempData["Cols"]; j++)
{
<input id="Checkbox + #i" name = "Category" type="checkbox" style="width:50px;" value="#TempData["[" + i.ToString() + "][" + j.ToString() + "]"]"/>
#TempData["[" + i.ToString() + "][" + j.ToString() + "]"]
}
}
#*#Html.LabelFor(model => model.CategoryName)*#
</div>
<div style="float:right;">
<label id="lblcategoryrequired" style="color:Red">#Html.ValidationMessageFor(model => model.CategoryName)</label>
</div>
</div>
</div>
<div>
<p style="display: inline; float: left;">
#Html.Label("lblsubjet", "Subject", new { style = "Width:100px; float: left;" })
#*#Html.TextBox("txtsubject", "", new { style = "Width:700px;" })*#
#Html.TextBoxFor(model => model.PostSubject, new { style = "Width:400px; maxlength=400;" })
<label id="lblsubjectrequired" style="color:Red">#Html.ValidationMessageFor(model => model.PostSubject)</label>
</p>
</div>
<div>
<p style="display: inline; float: left;">
#Html.Label("lblcontent", "Content", new { style = "Width:100px; float: left; Vertical-align:top;" })
#*#Html.TextArea("txtcontent","", new { style = "Width:700px; height:200px; maxlength=700;" })*#
#Html.TextAreaFor(model => model.PostContent, new { style = "Width:400px; height:200px; maxlength=400;" })
</p>
</div>
<div>
<p style="display: inline; float: left;">
#Html.Label("lblblank", "a", new { style = "Width:100px; float: left; Color:#372412" })
<input type="submit" value="Add" id="btnadd" style="width: 100px;" class="button" />
&nbsp&nbsp&nbsp&nbsp
<a id="Cancel" href="~/Home/Home"> <input type="button" value="Cancel" id="btncancel" class="button" style="width: 100px;" /></a>
</p>
</div>
</div>
#Html.ValidationSummary(true)
}
</div>
</div>
</div>
</div>

I don't understand your question 100%. But if I were to understand it then I don't think it will work the way that you need it to work (I might be mistaken). I would suggest that you move away from your partial view and just pass in one view model that you can use to populate both sections. View models are there to represent your data on a view.
I'm going to give you a basic sample that you can modify and use in your scenario. Lets say we have a customer and this customer can have 1 or many addresses. So a basic representation of these 2 models could look like this:
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<Address> Addresses { get; set; }
}
public class Address
{
public int Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
}
And now on your details view you want to display the customer's details and the addresses of this customer. So we have 2 models (customer and address) that you are displaying on 1 view.
public ActionResult Details(int id)
{
Customer customer = customerRepository.GetById(id);
if (customer != null)
{
customer.Addresses = addressRepository.GetAddressesForCustomer(customer.Id);
}
// The above 2 steps can be done in 1 repository call
// Now populate your view model with the above details
// This can also be 1 or 2 lines when you use something like Auto Mapper
CustomerDetailsViewModel viewModel = new CustomerDetailsViewModel
{
viewModel.CustomerId = customer.Id,
viewModel.CustomerFirstName = customer.FirstName,
viewModel.CustomerLastName = customer.LastName,
viewModel.CustomerAddresses = customer.Addresses
};
return View(viewModel);
}
Your view model:
public class CustomerDetailsViewModel
{
public int CustomerId { get; set; }
public string CustomerFirstName { get; set; }
public string CustomerLastName { get; set; }
public IEnumerable<Address> CustomerAddresses { get; set; }
}
So now you have 1 view model populated from 2 different models. Now all that you have to do on your view is to use this view model to display data:
#model YourProject.ViewModels.Customers.CustomerDetailsViewModel
#Model.CustomerId<br />
#Model.CustomerFirstName<br />
#Model.CustomerLastName<br /><br />
#foreach (var address in #Model.CustomerAddresses)
{
<div>
#address.Id<br />
#address.AddressLine1<br />
#address.AddressLine2<br />
#address.AddressLine3<br />
</div>
}
I hope this helps.

You should use a view model that represents the data required to render your view. You could either expose the models directly on the view model (violating LoD), or delegate the calls to the view model to the underlying models (violating the DRY principle).

Related

How to create object that contains a list of object in a single form?

public class Basket
{
public int Id { get; set; }
public string Sharp { get; set; }
public string Material { get; set; }
public List<Fruit> Fruits { get; set; }
}
public class Fruit
{
public int Id { get; set; }
public string Color { get; set; }
public string Taste { get; set; }
}
With the above example, how could I create both Basket and Fruit in the same asp-form without using any JavaScript?
<form method="post" asp-controller="Basket" asp-action="Create">
<input asp-for="Material" />
<input asp-for="Sharp" />
#*I would like to also create custom amounts of new Fruit in this form.*#
<input type="submit" value="Submit" />
</form>
If my razor form is defined as the above example, how could I create custom amounts of Fruit and create Basket at the same form? It is possible to avoid using JavaScript in this case?
It is possible to avoid using JavaScript in this case?
Based on your scenario and current architecture what you need to do is, there should be a table where you would be adding your fruit object as it's a List<Fruit> Fruit kind of. As per your given code, your output should be as below:
So, I would say, Javascript would make it easier. If you would like to avoid javascript it wouldn't be impossible but would be costly and complex.
how could I create custom amounts of Fruit and create Basket at the
same form?
You could follow the below steps to achieve what you are trying to implement.
View:
#model DotNet6MVCWebApp.Models.Basket
<form method="post" asp-controller="Yonny" asp-action="Create">
<div class="form-group">
<label asp-for="Material" class="col-md-2 form-label"></label>
<input asp-for="Material" class="col-md-6 form-control" />
<span asp-validation-for="Material" class="form-span-error"></span>
</div>
<div class="form-group" style="padding-bottom:20px">
<label asp-for="Sharp" class="col-md-2 form-label"></label>
<input asp-for="Sharp" class="col-md-6 form-control" />
<span asp-validation-for="Sharp" class="form-span-error"></span>
</div>
#*I would like to also create custom amounts of new Fruit in this form.*#
<div style="padding-bottom:20px">
<button type="button" class="btn btn-primary" onclick="AddRow()">Add Fruit</button>
</div>
<div id="dataTable">
<table>
<thead>
<tr>
<th>Id</th>
<th>Color</th>
<th>Taste</th>
</tr>
</thead>
<tbody id="FruitList" data-count="0">
</tbody>
</table>
</div>
<input type="submit" class="btn btn-success" value="Submit" />
</form>
#section Scripts {
<script>
/*
. Hidding table on load
*/
document.getElementById('dataTable').style.display ='none';
function AddRow()
{
var countVal = parseInt($('#FruitList').attr('data-count'));
var html = '';
html += '<tr>';
html += '<td><input type="text" name="Fruits[' + countVal + '].Id" class="form-control"/></td>';
html += '<td><input type="text" name="Fruits[' + countVal + '].Color" class="form-control"/></td>';
html += '<td><input type="text" name="Fruits[' + countVal + '].Taste" class="form-control"/></td>';
html += '</tr>';
$('#FruitList').append(html);
countVal += 1;
$('#FruitList').attr('data-count', countVal);
/*
. Showing table when adding item into
*/
document.getElementById('dataTable').style.display ='block';
}
</script>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("Id,Material,Sharp,Fruits")] DotNet6MVCWebApp.Models.Basket basket)
{
if (ModelState.IsValid)
{
//Save Basket
_context.Add(basket);
await _context.SaveChangesAsync();
//Add Fruits List
foreach (var item in basket.Fruits)
{
_context.Add(item);
await _context.SaveChangesAsync();
}
return RedirectToAction(nameof(Create));
}
return View(basket);
}
Note:
If you somehow got null data while sending request to controller make sure your binding property that is Bind("Id,Material,Sharp,Fruits") are same as name="Fruits[' + countVal + '].Id" inside the javascript function
Output:

How can i take many textboxes' value on Post in MVC

i have a problem about MVC, but first I am sorry for my english :D .
Now i am trying to make a form for users and i have a critical issue when i want connect to values with database.
My Form is like this : https://i.hizliresim.com/vJ6r2p.png
Models :
[Table("Testers")]
public class Testers
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(50),Required]
public string testerName { get; set; }
public ICollection<Scores> Scores { get; set; }
}
[Table("Technologies")]
public class Technologies
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(50)]
public string technologyName { get; set; }
[StringLength(50)]
public string type { get; set; }
}
[Table("Scores")]
public class Scores
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[DefaultValue(0)]
public int score { get; set; }
public virtual Testers tester { get; set; }
public virtual Technologies technology { get; set; }
}
ViewModels:
public class TechnologiesView
{
public List<Technologies> Technologies { get; set; }
public Scores Scores { get; set; }
}
Controller :
public ActionResult Page2()
{
TechnologiesView allTechs = new TechnologiesView();
allTechs.Technologies = db.Technologies.ToList();
return View(allTechs);
}
View:
#model TechnologiesView
#{
ViewBag.Title = "Page2";
}
<style>
#lang {
font-size: 15px;
color: gray;
}
#tech {
font-size: 13px;
color: gray;
}
</style>
<div class="container">
<div class="row col-xs-12 bilgi" style="color:black">
#HelperMethods.Title("Kendini Skorla!")
<br />
<i>Bilgi Düzeyini 0 ile 5 puan arasında notlar mısın? (0=Hiç 5= İleri Seviye)</i>
</div>
</div>
<hr />
#using (Html.BeginForm())
{
<div class="container-fluid" style="padding-left:50px; margin:0px">
<div class="row" id="lang">
#foreach (Technologies techs in Model.Technologies)
{
if (techs.type == "lang")
{
<div class="col-md-1 col-sm-2 col-xs-6">
#(techs.technologyName)
</div>
<div class="col-md-1 col-sm-2 col-xs-6">
(#(Html.TextBoxFor(x => x.Scores.score, new
{
id = techs.ID,
name = "techID",
style = "display:inline; width:20px; height:20px; font-size:smaller; padding:0px; text-align:center",
#class = "form-control"
})))
</div>
}
}
</div>
<hr style="color:black" />
<div class="row" id="tech">
#foreach (Technologies techs in Model.Technologies)
{
if (techs.type == "tech")
{
<div class="col-md-1 col-sm-2 col-xs-6" id="tech">
#(techs.technologyName)
</div>
<div class="col-md-1 col-sm-2 col-xs-6">
#Html.HiddenFor(x=>techs.ID)
(#(Html.TextBoxFor(x => x.Scores.score, new
{
id = techs.ID,
name = "techID",
style = "display:inline; width:20px; height:20px; font-size:smaller; padding:0px; text-align:center",
#class = "form-control"
})))
</div>
}
}
</div>
<hr />
<div class="row col-xs-12" id="lang">
<span>Kullandığınız IDE’ler (yazınız)</span>
<br />
<div style="margin-bottom:10px; text-align:center">
#HelperMethods.TextArea("Ide", 3)
</div>
</div>
<div style="text-align:right; margin-bottom:10px">
#HelperMethods.Button("btnPage2")
</div>
</div>
}
Now user has to give a score to him/herself for every technologies or languages and after this i want to when user click to button "Follow the next page(it's turkish)" i will select the last saved user from maxID value in Testers and i have to connect scores with technologies and testers but i don't know how can i get textboxes' values and which technology's value is this value on post :D
You generating form controls which have no relationship at all to your model (which is also wrong anyway). Never attempt to change the name attribute when using the HtmlHelper methods (and there is no reason to change the id attribute either)
Next, you cannot use a foreach loop to generate form controls for a collection. You need a for loop or EditorTemplate to generate the correct name attributes with indexers. Refer this answer for a detailed explanation.
Then you cannot use a if block inside the loop (unless you include a hidden input for the collection indexer), because by default the DefaultModelBinder required collection indexers to start at zero and be consecutive.
First start by creating view models to represent what your want to display/edit in the view.
public class ScoreVM
{
public int ID { get; set; }
public string Name { get; set; }
public int Score { get; set; }
}
public class TechnologiesVM
{
public List<ScoreVM> Languages { get; set; }
public List<ScoreVM> Technologies { get; set; }
public string Notes { get; set; } // for your textarea control
}
Note you will probably want to add validation attributes such as a [Range] attribute for the Score property
In the GET method, initialize and populate your view model and pass it to the view
public ActionResult Page2()
{
IEnumerable<Technologies> technologies = db.Technologies;
TechnologiesVM model = new TechnologiesVM
{
Languages = technologies.Where(x => x.type == "lang")
.Select(x => new ScoreVM{ ID = x.ID, Name = x.technologyName }).ToList(),
Technologies = technologies.Where(x => x.type == "tech")
.Select(x => new ScoreVM{ ID = x.ID, Name = x.technologyName }).ToList(),
};
return View(model);
}
and in the view
#model TechnologiesVM
....
#using (Html.BeginForm())
{
....
#for (int i = 0; i < Model.Languages.Count; i++)
{
#Html.HiddenFor(m => m.Languages[i].ID)
#Html.HiddenFor(m => m.Languages[i].Name)
#Html.LabelFor(m => m.Languages[i].Score, Model.Languages[i].Name)
#Html.TextBoxFor(m => m.Languages[i].Score)
#Html.ValidationMessageFor(m => m.Languages[i].Score)
}
#for (int i = 0; i < Model.Languages.Count; i++)
{
.... // repeat above
}
#Html.LabelFor(m => m.Notes)
#Html.TextAreaFor(m => m.Notes)
#Html.ValidationMessageFor(m => m.Notes)
<input type="submit" />
}
and the POST method will be
public ActionResult Page2(TechnologiesVM model)
{
if (!ModelState.IsValid)
{
return View(model);
}
... // save the data and redirect
}

MVC Model Binding for EditorFor

I have three class types Search, BaseSearch and TextSearch of the following relation. Search is composed of a List<BaseSearch> and TextSearch inherits from BaseSearch, BaseSearch is abstract.
Now I would like to use Html helper to draw a list of TextSearch, EditorTemplate is below
#model GenericSearch.Models.TextSearch
<table class="form-group container">
<tr class="row">
<td class=" col-sm-2 " style="display: table-cell; vertical-align: middle;height: 50px; ">
#Html.LabelFor(x => x.Label, Model.Label, new { #class = "control-label pull-right" })
</td>
<td class=" col-sm-2 " style="display: table-cell; vertical-align: middle;height: 50px; ">
#Html.DropDownListFor(m => m.Comparators, new SelectList(Model.Comparators, "Value", "Text"), new { #class = "form-control", style = "width:150px" })
</td>
<td class="col-sm-8 form-inline" style="display: table-cell; vertical-align: middle;height: 50px;">
#Html.TextBoxFor(x => x.Value, new { #class = "form-control" })
</td>
</tr>
</table>
I have a razor view for Index as below
#model GenericSearch.Models.Search
<div class="row">
#using (#Html.BeginForm("Index", "Home", FormMethod.Post))
{
{
#Html.EditorFor(m => m.List)
<div class="form-group">
<div class="col-sm-12 text-center">
<button type="submit" class="btn btn-primary">Apply filters</button>
</div>
</div>
}
}
</div>
And two Index action at the controller as below
public ActionResult Index()
{
Search search = new Models.Search();
search.List= new List<BaseSearch>();
TextSearch text = new TextSearch();
text.Label = "Text1";
search.MyProperty.Add(text);
return View(search);
}
[HttpPost]
public ActionResult Index(Search search)
{
return View(search);
}
This setting is rendered fine, however when I fill the rendered text boxes and post it through the submit button, I am expecting to receive the Search class populated with the List<TextSearch> that has properties filled with the values entered by the user at the HttpPost Index. But I get an error saying that this can't be done because BaseClass is abstract, when I remove the abstract keyword from the BaseClass the Search class gets instantiated but with a List<BaseSearch> instead of a List<TextSearch> also it has its properties empty, not filled with the data user entered. What am I missing here?
EDIT
public class Search
{
public List<BaseSearch> List { get; set; }
}
public abstract class BaseSearch
{
string label;
protected List<Comparator> comparators;
public string Label
{
get
{
return label;
}
set
{
label = value;
}
}
public List<Comparator> Comparators
{
get
{
return comparators;
}
set
{
comparators = value;
}
}
public BaseSearch()
{
comparators = new List<Models.Comparator>();
}
}
public class TextSearch : BaseSearch
{
string _value;
public string Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
public TextSearch() : base()
{
comparators.Add(new Comparator() { Value = -1, Text = Resources.Choose });
comparators.Add(new Comparator() { Value = 1, Text = Resources.StartWith });
comparators.Add(new Comparator() { Value = 2, Text = Resources.Contains });
}
}

Data Annotation for Contact form

I have this situation:
Model class:
public class ContatoModel
{
private string nome;
private string email;
private string telefone;
public ContatoModel()
{
}
public ContatoModel(string nome, string email, string telefone)
{
this.nome = nome;
this.email = email;
this.telefone = telefone;
}
public string Assunto { get; set; }
[Required(ErrorMessage = "Nome Obrigatório")]
public string Nome
{
get
{
return this.nome;
}
set
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Nome" });
nome = value;
}
}
[Required(ErrorMessage = "Email Obrigatório")]
public string Email { get; set; }
[Required(ErrorMessage = "Telefone Obrigatório")]
public string Telefone { get; set; }
public string Comentarios { get; set; }
}
A View with:
#using (Html.BeginForm("EnviarContato", "Contato"))
{
<div style="float: left; margin-bottom: 15px;">
#Html.Label("Assunto")<br />
#Html.DropDownList("ddlAssunto", assuntos, new {#class="dropdown"})
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
#Html.Label("Nome Completo", new { #class = "textfield" })<br />
#Html.TextBox("txtNome", "", new { #class = "textfield" })
#Html.ValidationMessage("Nome", "*")
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
#Html.Label("Email")<br />
#Html.TextBox("txtEmail", "", new { #class = "textfield" })
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
#Html.Label("Telefone")<br />
#Html.TextBox("txtTelefone", "", new { #class = "textfield" })
</div>
<div style="clear: both"></div>
<div style="float: left; margin-bottom: 10px;">
#Html.Label("Comentários")<br />
#Html.TextArea("txtComentarios")
</div>
<div style="clear: both"></div>
<div style="float: left; margin: 2px 20px 0px 255px;">
#*<input type="image" src="/Content/images/button_send2.gif" />*#
<input type="submit" value="Enviar" title="Enviar" />
</div>
}
And this method in controller:
[HttpPost]
public ActionResult EnviarContato(FormCollection values)
{
try
{
string assunto = values["ddlAssunto"];
string nome = values["txtNome"];
string email = values["txtEmail"];
string telefone = values["txtTelefone"];
string comentarios = values["txtComentarios"];
model.Assunto = assunto;
model.Nome = nome;
model.Email = email;
model.Telefone = telefone;
model.Comentarios = comentarios;
EnviarContato();
return RedirectToAction("Index", new { envio = "OK" });
}
catch (ValidationException ex)
{
throw new ValidationException(ex.Message); //return RedirectToAction("Index", new { envio = "NOK" });
}
}
I can't do data annotation client works. The ValidationException occurs in server side, but I'd like to see the validation client messages, but it doesn't work. The jQuery files are still loading in my master page.
Another problem is that my view has a combo, loaded by the assunto variable, and I don't know how to include it in validation, to force user select one.
My model class is not for a data entity. It is just to receive form values, to validate and if everything is ok, send the email.
I cant do data annotation client works. The ValidationException occurs in server side, but I´d like to see the validation client messages, but it doesnt work. The jquery files are still loading in my master page.
The files jquery.validate.js and jquery.validate.unobtrusive.js must be included in the page.
The <add key="UnobtrusiveJavaScriptEnabled" value="true" /> must be in the Web.Config.
Another problem is that my view has a combo, loaded by the assunto variable, and I dont know how to include it in validation, to force user select one.
One of Options with empty value should be in your DropDownList. For example "--Select One--".

Using IList<T> to bind values in .cshtml

My Controler Content is:
public ActionResult Step2()
{
Step2BusinessLogic step2BusinessLogic = new Step2BusinessLogic();
Step2ViewModel step2ViewModel = step2BusinessLogic.CreateStep2ViewModel();
return View(step2ViewModel);
}
[HttpPost]
public ActionResult Step2()
{
....
}
Step2ViewModel has a property like...
public class Step2ViewModel : MultiStepBaseViewModel
{
public IList<LayoutDetail> LayoutConfig { get; set; }
}
Business Logic Class is Like....
public class Step2BusinessLogic
{
public Step2ViewModel CreateStep2ViewModel(string Id)
{
Step2ViewModel step2ViewModel = new Step2ViewModel();
step2ViewModel.MultiStepId = new Guid(Id);
step2ViewModel.LayoutConfig = GetLayout();
return createEmailStep2ViewModel;
}
public List<LayoutDetail> GetLayout()
{
List<LayoutDetail> layoutList = new List<LayoutDetail>();
LayoutDetail layout1 = new LayoutDetail();
layout1.LayoutID = 1;
layout1.LayoutTitle = "1 Column";
layout1.LayoutImg = "~/img/create/layout/layout-1.png";
layout1.LayoutImgPrev = "img/create/layout/layout-1-preview.png";
layoutList.Add(layout1);
LayoutDetail layout2 = new LayoutDetail();
layout2.LayoutID = 2;
layout2.LayoutTitle = "1:2 Column";
layout2.LayoutImg = "~/img/create/layout/layout-2.png";
layout2.LayoutImgPrev = "img/create/layout/layout-2-preview.png";
layoutList.Add(layout2);
.........(12 Items)
return layoutList;
}
}
public class LayoutDetail
{
public int LayoutID { get; set; }
public string LayoutTitle { get; set; }
public string LayoutImg { get; set; }
public string LayoutImgPrev { get; set; }
}
On My .cshtml view i want something Like this...
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.MultiStepId)
#Html.ValidationSummary(true)
#for (int i = 0; i < 12; i++)
{
<div class="grid_3 tcenter">
<div class="divhighlight">
<div style="width: 165px; margin: 6px auto 4px auto;" class="f16 bold tcenter" id="helptrigger1">#LayoutConfig.Title</div>
<a class="fancybox" rel="layouts" href="#LayoutConfig.LayoutImgPrev" title="1 Column">
<img src="#LayoutConfig.LayoutImg" alt="1 Column" width="189" height="227" vspace="5" /></a>
<div style="width:189px; margin:auto">
<button class="button gobutton" style="margin-right: 40px; width: 165px;" value="#LayoutConfig.LayoutID">Select</button></div>
</div>
</div>
}
I want to bind the values of IList<LayoutDetail> property of Step2ViewModel to the controls of .cshtml page. I tried several other thing but could not Succeed
You are missing this #Model.LayoutConfig[i]
#for (int i = 0; i < Model.LayoutConfig.Count(); i++)
{
<div class="grid_3 tcenter">
<div class="divhighlight">
<div style="width: 165px; margin: 6px auto 4px auto;" class="f16 bold tcenter" id="helptrigger1">#Model.LayoutConfig[i].LayoutTitle </div>
<a class="fancybox" rel="layouts" href="#Model.LayoutConfig[i].LayoutImgPrev" title="1 Column">
<img src="#Model.LayoutConfig[i].LayoutImg" alt="1 Column" width="189" height="227" vspace="5" /></a>
<div style="width:189px; margin:auto">
<button class="button gobutton" style="margin-right: 40px; width: 165px;" value="#Model.LayoutConfig[i].LayoutID">Select</button></div>
</div>
</div>
}
You need use
#Model.LayoutConfig[i].LayoutImg
Instead of
#LayoutConfig.LayoutImg
And of cource for other situations
#LayoutConfig.LayoutID
#LayoutConfig.LayoutImgPrev

Resources