MVC 4 ASPX to Razor - asp.net-mvc-3

New to Razor, trying to convert the following:
<select id="Province" name="Province" style="width: 235px; background-color: #FFFFCC;">
<%
string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName;
if (Model != null && !String.IsNullOrEmpty(Model.Province))
selectedProvinceName = Model.Province;
else
selectedProvinceName = ConfigData.DefaultProvinceName;
foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName ? " selected=\"selected\"" : String.Empty;
%>
<option value="<%= anEntry %>" <%= selectedTextMark %>>
<%= anEntry %></option>
<%
}
%>
</select>
</td>
The Razor:
<select id="Province" name="Province" style="width: 235px; background-color: #FFFFCC;">
#string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName;
if (Model != null && !String.IsNullOrEmpty(Model.Province))
selectedProvinceName = Model.Province;
else
selectedProvinceName = ConfigData.DefaultProvinceName;
foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName ? " selected=\"selected\"" : String.Empty;
<option value="#anEntry" #selectedTextMark>
#anEntry</option>
}
</select>
</td>
I get this error:
Invalid expression term 'string' in #string[] provinces = viewBag.ProvincesForSelectedCountry;
Thanks in advance.

You need
#{
string[] provinces = ViewBag.ProvincesForSelectedCountry;
and then a closing } before the </select> tag.

Related

After Submit TotalPages Throws error

I have a little problem with my paging ("double TotalPage = #ViewBag.TotalPages; on Partial View"), after submiting on Create or Edit the paging throws the following error: "Cannot convert null to 'double' because it is a non-nullable value type". I have created a partial view that contains the list (Crud Operations using Ajax), all works fine, I can go to different pages in the list but when I submit a new row or edit an existing one it displays that error. Here is the code for it:
public ActionResult IndexApp(string Page)
{
var appc = objBs.appointmentdiaryBs.GetALL();
appc = from ac in db.tbl_Appoiment_Diary
select ac;
ViewBag.TotalPages = Math.Ceiling(objBs.appointmentdiaryBs.GetALL().Count() / 5.0);
int page = int.Parse(Page == null ? "1" : Page);
ViewBag.Page = page;
appc = appc.Skip((page - 1) * 5).Take(5);
ViewBag.Count = db.tbl_Appoiment_Diary.SqlQuery("SELECT * FROM dbo.tbl_Appoiment_Diary").Count();
return View(appc.ToList());
}
here is the partial view:
#model IEnumerable<BOL3.tbl_Appoiment_Diary>
<div class="table-responsive">
<table class="table" id="tbl" style="border-collapse: separate; border: solid grey 1px; border-radius: 6px; -moz-border-radius: 6px;">
<thead>
<tr style="background-color:aqua">
<th>
#Html.ActionLink("Title", "Title", "IndexApp", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc" ? "Des" : "Asc"), SortBy = "Title", page = (ViewBag.Page == null ? "1" : ViewBag.Page) })
</th>
<th>
#Html.ActionLink("Scheduled Date and Time", "DateTimeScheduled", "IndexApp", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc" ? "Des" : "Asc"), SortBy = "DateTimeScheduled", page = (ViewBag.Page == null ? "1" : ViewBag.Page) })
</th>
<th>
#Html.ActionLink("Appointment Lenght", "AppointmentLenght", "IndexApp", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc" ? "Des" : "Asc"), SortBy = "AppointmentLenght", page = (ViewBag.Page == null ? "1" : ViewBag.Page) })
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTimeScheduled)
</td>
<td>
#Html.DisplayFor(modelItem => item.AppointmentLenght)
</td>
<td style="align-content:center">
Edit |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
#{
double TotalPage = #ViewBag.TotalPages;
}
<ul class="pagination pagination-sm">
#for (int i = 1; i <= TotalPage; i++)
{
if (i == ViewBag.Page)
{
<li class="active">#Html.ActionLink(i.ToString() + " ", "IndexApp", new { SortOrder = (ViewBag.SortOrder == null ? "Asc" : ViewBag.SortOrder), SortBy = (ViewBag.SortBy == null ? "Title" : ViewBag.SortBy), Page = i })</li>
}
else
{
<li>#Html.ActionLink(i.ToString() + " ", "IndexApp", new { SortOrder = (ViewBag.SortOrder == null ? "Asc" : ViewBag.SortOrder), SortBy = (ViewBag.SortBy == null ? "Title" : ViewBag.SortBy), Page = i })</li>
}
}
</ul>
</div>
and here is the Index view:
<div id="main-div">
<div class="clearfix"> </div>
<div class="clearfix"> </div>
<div class="container">
Adauga
<br />
<div id="div-record1">
#Html.Partial("_Detail")
</div>
</div>
</div>

For loop not only passing once

String[] expected = new String[10];
//{"Acapulco","Frankfurt","London","New York","Paris","Portland","San Francisco","Seattle","Sydney","Zurich"};
expected[0] = "Acapulco";
expected[1] = "Frankfurt";
expected[2] = "London";
expected[3] = "New York";
expected[4] = "Paris";
expected[5] = "Portland";
expected[6] = "San Francisco";
expected[7] = "Seattle";
expected[8] = "Sydney";
expected[9] = "Zurich";
List<WebElement> allOptions = driver.findElements(By.name("fromPort"));
// match the fromPort list value against the expected Array
for (int i = 0 ; i < (expected.length) && i < allOptions.size(); i++) {
String optionValue = allOptions.get(i).getAttribute("value");
if (optionValue.equals(expected[i])) {
System.out.println("PASSED on: " + optionValue + " we had: "+ expected[i] );
}
else {
System.out.println("FAILED on: " + optionValue + " we expected: " + expected[i]);
}
}
//close Firefox
driver.close();
When executing the loop is only going round once then it exists... So it executes:
PASSED on: Acapulco we had: Acapulco
then exits the loop...
This is following on from my other comment: My Other Comment
New to all this Java and Selenium....
I am assuming its something to do with the Size of it only being 1; but not sure how to increase/overcome this
HTML snippet added as requested in comments:
<tr>
<td align="right">
<font face="Arial, Helvetica, sans-serif" size="2">
<b>
Departing
From:
</b>
</font>
</td>
<td>
<select name="fromPort">
<option value="Acapulco"></option>
<option value="Frankfurt"></option>
<option value="London"></option>
<option value="New York"></option>
<option value="Paris"></option>
<option value="Portland"></option>
<option value="San Francisco"></option>
<option value="Seattle"></option>
<option value="Sydney"></option>
<option value="Zurich"></option>
</select>
Please use the following code to select all options. The code you are trying to use selects the select element itself and not the options.
List<WebElement> allOptions = driver.findElement(By.name("fromPort")).findElements(By.tagName("option"));

Jquery Validation on Dom not displaying message

I stumbled upon some code that has jQuery validation which is triggered after an ajax call that adds items to the DOM. The validation is working but the message is missing. just the field is highlighted. I have been playing with this for a while to get it to work, but so far no luck. Any ideas, thoughts appreciated.
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var otherIncomesCount = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var count = otherIncomesCount;
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
});
The validation succeeds for both required on additionalIncomeTypeIDMenu, and required and positive on amountTextBox, but the messages for both fail to show up:
function addOtherIncomeValidation(container) {
if (container) {
var additionalIncomeTypeIdMenu = $(container).find('select.other-income-type-id');
var amountTextBox = $(container).find('input.other-income-amount');
$(additionalIncomeTypeIdMenu).rules('add', {
required: true,
messages: {
required: 'Please select an income type'
}
});
$(amountTextBox).rules('add', {
required: true,
positive: true,
messages: { positive: 'must be positive number'
}
});
}
}
BTW The ajax call returns a partial EditorTemplate here, which you can see uses ValidationMessageFor.
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />#Html.ValidationMessageFor(x => x.AdditionalIncomeTypeId)
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />#Html.ValidationMessageFor(x => x.Amount)
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
HTML:
<div id="OtherIncome" class="applicant-section">
<h2 class="header2">Other Income</h2>
<div class="cornerForm">
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_0__Id" name="OtherIncome[0].Id" type="hidden" value="385" />
<label class="other-income-type-id-label" for="OtherIncome_0__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_0__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_0__AdditionalIncomeTypeId" name="OtherIncome[0].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option selected="selected" value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_0__Amount" name="OtherIncome[0].Amount" style="" type="text" value="0.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XNxxxxx753/385">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_1__Id" name="OtherIncome[1].Id" type="hidden" value="412" />
<label class="other-income-type-id-label" for="OtherIncome_1__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_1__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_1__AdditionalIncomeTypeId" name="OtherIncome[1].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option selected="selected" value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_1__Amount" name="OtherIncome[1].Amount" style="" type="text" value="22.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XN42093753/412">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div id="additional-other-income"></div>
<input id="numberOfNewOtherIncomes" name="numberOfNewOtherIncomes" type="hidden" value="0" />
<input data-val="true" data-val-number="The field OriginalOtherIncomeTotal must be a number." id="OriginalOtherIncomeTotal" name="OriginalOtherIncomeTotal" type="hidden" value="22.0000" />
<a class="editable-link" href="/Applicant/AddOtherIncome?appId=XNxxxxx753" id="add-other-income-link">Add Other Income</a>
</div> </div>
Validation code:
$.validator.addMethod('positive', function(value, element) {
var check = true;
if (value < 0) {
check = false;
}
return this.optional(element) || check;
}, "Value must be a positive number."
);
I didn't think I would find my own answer but I did. first I have to apologize for my response to #Sparky with his request for rendered HTML. I did a "View page source" but that didn't include all the stuff which was added from the ajax call after the server delivered it's stuff. I suspect if I did include the extra DOM stuff at first, you would have pinpointed the issue sooner. My bad. Now on to the answer.
It appears that when injecting an EditorTemplate into the DOM in the way shown above, it doesn't properly process the page like you would expect in MVC. The code for #Html.ValidationMessageFor simply does not get parsed AT ALL. I am a little new to validation as you can see so I don't know why it behaves this way. To solve my problem here is what I did:
I updated my Editor Template slightly to look like this:
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />
#Html.ValidationMessageFor(x=>x.AdditionalIncomeTypeId)
<span id="AdditionalIncomeTypeIdValidation"></span>
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />
#Html.ValidationMessageFor(x=>x.Amount)
<span id="amountValidation"></span>
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
Notice the new span tags, which is are added next to the #Html.ValidationMessageFor.
then in my success function from the ajax call in javascript I made these changes:
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var count = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var amountValidation = $(item).find('#amountValidation');
var typeIdValidation = $(item).find('#AdditionalIncomeTypeIdValidation');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
amountValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'Amount')
.attr('data-valmsg-replace','true');
typeIdValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'AdditionalIncomeTypeId')
.attr('data-valmsg-replace','true');
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
notice I am manually adding in the missing validation spans that were not rendering. Now the validation message shows up at validation! Yay. I am not sure however that this is the best fix. It looks and smells like a hack, but I got it to work. I am sure it can be done a better way. Thanks again for interaction and feedback.

What to put in Inherits part in Partial in mvc3

i have in my controller and im not sure if i have it correct
[HttpGet]
[NoCache]
public ActionResult ListCommentsOnNews(int newsId, string newsComment) ???
{
//code here with return
}
in my Article.aspx view:
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null)
{ %>
<% foreach (var newsItem in Model.Results.NewsComments)
{ %>
<% Html.RenderPartial("SetCommentOnNews", newsItem); %>
<%} } %>
</div>
then my partial ListCommentsOnNews.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<???>" %>
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png" />
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %> //get error here
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div> //and get error here
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
my controller:
[HttpGet]
public ActionResult Article(int id, int? page)
{
var news = ZincService.NewsService.GetNewsForId(id);
var allNewsComments = ZincService.NewsService.GetAllNewsCommentsForId(id, page.GetValueOrDefault(1), 10);
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
if (news == null || news.PublishingState != PublishingState.Live)
return RedirectToAction("NotFound");
if (allNewsComments != null)
{
var user = ZincService.GetUserForId(currentUser.UserId);
if (user == null || user.Customer.CustomerId != CurrentCustomer.CustomerId)
return DataNotFound();
ViewBag.Avatar = user.UserImage;
ViewBag.UserName = user.Firstname + " " + user.Surname;
NewsCommentsViewModel model = (NewsCommentsViewModel)SetNewsArticleViewModel(news, new NewsCommentsViewModel());
foreach (var newsItem in allNewsComments.NewsComments)
{
model.Results = allNewsComments;
model.PageSize = 10;
model.CurrentPage = page.GetValueOrDefault(1);
}
return View(model);
}
else
{
return View(SetNewsArticleViewModel(news,null));
}
}
[NonAction]
private NewsArticleViewModel SetNewsArticleViewModel(Entities.News.News news, NewsArticleViewModel viewModel)
{
viewModel.News = news;
viewModel.IsFavourite = ZincService.FavouriteService.IsFavouriteForUser(CurrentUser.UserId, news);
viewModel.DownloadAttachments = news.NewsAttachments.Where(x =>
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Excel ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.PDF ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.PowerPoint ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Word);
viewModel.EmbedAttachments = news.NewsAttachments.Where(x =>
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Video);
return viewModel;
}
i get errors on the newsItem parts stating that it does not exist in the current context.
can some one help me right please?
As i inferred from code you posted, problem is with you'r usage of Model.you are trying to use model properties,but you are not doing it correctly.try following :
<%
Model.CommentDate
%>
instead of
<%: newsItem.CommentDate %> //get error here

Empty Enumeration in post method

I have this view
#model IEnumerable<ViewModelRound2>
... <snip> ...
#{
using (Html.BeginForm(new { round1Ring3Bids = Model }))
{
if (Model != null && Model.Count() > 0)
{
... <snip> ...
#for (var x = 0; x < Model.Count(); x++)
{
ViewModelRound2 viewModelRound2 = Model.ElementAt(x);
Bid bid = viewModelRound2.Bid;
string userName = #bid.User.Invitation.Where(i => i.AuctionId == bid.Lot.Lot_Auction_ID).First().User.User_Username;
<tr>
<td>
#userName
</td>
<td>
#bid.Bid_Value
</td>
<td>
#Html.EditorFor(c => c.ElementAt(x).SelectedForRound2)
</td>
</tr>
}
</table>
<div class="buttonwrapper2">
<input type="submit" value="Select"/>
</div>
}
}
}
I have a post method that this goes to when the submit button is hit
[HttpPost]
public ActionResult Round2Manager(IEnumerable<ViewModelRound2> round1Ring3Bids)
Problem is that the enumeration is always empty. Why is this?
Problem is that the enumeration is always empty. Why is this?
Because you are not respecting the wire format that the default model binder expects to bind collections.
The following:
#Html.EditorFor(c => c.ElementAt(x).SelectedForRound2)
generates absolutely wrong names for your input fields.
I would recommend you using editor templates to avoid those kind of problems:
#model IEnumerable<ViewModelRound2>
#using (Html.BeginForm())
{
if (Model != null && Model.Count() > 0)
{
<table>
#Html.EditorForModel()
</table>
<div class="buttonwrapper2">
<input type="submit" value="Select"/>
</div>
}
}
and then define a custom editor template for the ViewModelRound2 type (~/View/Shared/EditorTemplates/ViewModelRound2.cshtml) which will automatically be rendered for each element of this collection:
#model ViewModelRound2
# {
string userName = Model.Bid.User.Invitation.Where(
i => i.AuctionId == Model.Bid.Lot.Lot_Auction_ID
).First().User.User_Username;
}
<tr>
<td>
#userName
</td>
<td>
#Model.Bid.Bid_Value
</td>
<td>
#Html.EditorFor(c => c.SelectedForRound2)
</td>
</tr>
You will now notice how the text input fields have correct names:
name="[0].SelectedForRound2"
name="[1].SelectedForRound2"
name="[2].SelectedForRound2"
...
Compare this with your initial values.

Resources