ASP.Net MVC model as dictionary in view - asp.net-mvc

I would like to take the model as in view?
#model Dictionary<string,List<string>>
<table width="60%">
<tr class="ui-widget-header">
<td>
___Category___
</td>
<td>
___Detail___
</td>
</tr>
<tr>
<td>
#Model.Key
</td>
<td>
#Model.Count
</td>
</tr>
</table>
How could I do this?
here is my view with razor syntax.
Please help me.

Yes you can do it. Below is the sample
#model Dictionary<string,List<string>>
#foreach (KeyValuePair<string, List<string>> pair in Model)
{
<label> #pair.Key</label>
<div>
#foreach(string data in #pair.Value)
{
<span>#data </span>
}
</div>
}

Add #model Dictionary<string,List<string>> to your view (assuming Razor is used).

#model Dictionary<string, List<string>>
#foreach (var group in Model)
{
<h2>#group.Key</h2>
<table>
<tr>
<th>Title</th>
</tr>
#foreach (var aString in group.Value){
<tr>
<td>#aString </td>
</tr>
}
</table>
}

Related

Adding field to ASP.NET MVC view

I want to add one more field to my view. So basically, after displaying a town in the dropdown menu, I want to display the (*ABR) field as seen here.
As you can see from the picture, after Advance Ortopedical, I just want to add a filed called *ABR.
<table class="table datatable-responsive datatable-medical-map" id="medProviders" style="width:100%">
<thead>
<tr class="bg-info">
<th>Medical Provider (* Choose one)</th>
<th>Distance (miles)</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
#{
int i = 0;
foreach (var item in medProviders)
{
<tr class="sortList" style="cursor:pointer" id="increment-#i" data-id="#item.Id" data-lat="#item.Latitude" data-long="#item.Longitude">
<td>#item.Firstname</td>
<td id="distance-#i"></td>
<td id="duration-#i"></td>
</tr>
i++;
}
}
</tbody>
</table>
<p id="medicalValidation"></p>
Any suggestions or comments on how to do this in a simple way?
Please use this code. This will add 1 more field at the end of table.
#{
int i = 0;
foreach (var item in medProviders)
{
<tr class="sortList" style="cursor:pointer" id="increment-#i" data-id="#item.Id" data-lat="#item.Latitude" data-long="#item.Longitude">
<td>
#item.Firstname
<br>*ABR</br>
</td>
<td id="distance-#i"></td>
<td id="duration-#i"></td>
</tr>
i++;
}
}
</tbody>

MVC How to pass label data from view to controller?

I am trying to pass data from view to controller. I used BeginForm and i can pass data which users enter to textbox. But I want to also pass label data because label is filled automatically and i need to save this label text to database. How can i do?
View:
#using (Html.BeginForm("Room", "Booking", FormMethod.Post))
{
<table>
<tr>
<td align="left"><lable for="eventName">Description:</lable></td>
<td><input name="eventName" id="eventName"></td>
</tr>
<tr>
<td align="left"><lable for="startDate">Start Date : </td>
<td align="left"><label id="startDate" name="startDate" /></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td align="right" colspan="2">
<button type="submit" class="btn-primary" name="submit" id="submit">Save</button>
</td>
</tr>
<tr>
</tr>
</table>
}
Controller:
[HttpPost]
public ActionResult Room(FormCollection form)
{
using (BookingEntities ent = new BookingEntities ())
{
ReservationTBL Tbl = new ReservationTBL();
Tbl.Description = form["eventName"].ToString();
Tbl.startDate= form["startDate"].ToString();
ent.BookingTBL.Add(Tbl);
ent.SaveChanges();
}
return View();
}
The label data doesn't get send when you post your form. What you can do however is to add an input with type hidden that contains your label data.
Something like this:
<tr>
<td align="left"><label for="startDate">Start Date : </td>
<td align="left">
<label>#Model.StartDate</label>
<input type="hidden" name="startDate" value="#Model.StartDate" id="startDate"/>
</td>
</tr>

All model and Formcollection values are null, blank or don't exist in Firefox or Chrome

During debugging, my MVC model and Formcollection are blank with no values in FireFox (15) or Chrome (latest version).
During debugging using IE (9), I can see these values just fine.
Do you know what the solution is for this? This is very serious for public facing web sites not being able to do any programming angainst these browsers.
Here is my View...
#model PDFConverterModel.ViewModels.ViewModelTemplate_Guarantors
#{
ViewBag.Title = "BHG :: PDF Generator";
}
<h2>#ViewBag.Message</h2>
<div>
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="~/Images/logo.gif" />
</td>
</tr>
#using (Html.BeginForm("ProcessForm", "Home", FormMethod.Post))
{
<tr>
<td>
#(Html.Kendo().IntegerTextBox()
.Name("LoanID")
.Placeholder("Enter Loan ID")
)
</tr>
<tr>
<td>#Html.LabelFor(model => model.LoanType)
#Html.DisplayFor(model => model.LoanType)
</td>
<td>
<label for="ddlDept">Department:</label>
#(Html.Kendo().DropDownList()
.Name("ddlDept")
.DataTextField("DepartmentName")
.DataValueField("DepartmentID")
.Events(e => e.Change("Refresh"))
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetDepartments", "Home");
});
})
)
</td>
</tr>
if (Model.ShowGeneratePDFBtn == true)
{
if (Model.ErrorT == string.Empty)
{
<tr>
<td colspan="5">
<u><b>#Html.Label("Templates:")</b></u>
</td>
</tr>
<tr>
#for (int i = 0; i < Model.Templates.Count; i++)
{
<td>
#Html.CheckBoxFor(model => Model.Templates[i].IsChecked)
#Html.DisplayFor(model => Model.Templates[i].TemplateId)
</td>
}
</tr>
}
else
{
<tr>
<td>
<b>#Html.DisplayFor(model => Model.ErrorT)</b>
</td>
</tr>
}
if (Model.ErrorG == string.Empty)
{
<tr>
<td colspan="5">
<u><b>#Html.Label("Guarantors:")</b></u>
</td>
</tr>
<tr>
#for (int i = 0; i < Model.Guarantors.Count; i++)
{
<td>
#Html.CheckBoxFor(model => Model.Guarantors[i].isChecked)
#Html.DisplayFor(model => Model.Guarantors[i].GuarantorFirstName) #Html.DisplayFor(model => Model.Guarantors[i].GuarantorLastName)
</td>
}
</tr>
}
else
{
<tr>
<td>
<b>#Html.DisplayFor(model => Model.ErrorG)</b>
</td>
</tr>
}
}
<tr>
<td colspan="3">
<input type="submit" name="submitbutton" id="btnRefresh" value='Refresh' />
</td>
#if (Model.ShowGeneratePDFBtn == true)
{
<td>
<input type="submit" name="submitbutton" id="btnGeneratePDF" value='Generate PDF' />
</td>
}
</tr>
<tr>
<td colspan="5">
#Model.Error
</td>
</tr>
}
</table>
</div>
<script type="text/javascript">
$('btnRefresh').on('click', '#btnRefresh', function () {
Refresh();
});
function Refresh() {
var LoanID = $("#LoanID").val();
if (LoanID != "") {
document.forms[0].submit();
}
else {
alert("Please enter a LoanId");
}
}
</script>
I know this is a very old question, but answering this might help people like who are struggling with this issue.
I had a similar issue. The problem lies here:
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="~/Images/logo.gif" />
</td>
</tr>
#using (Html.BeginForm("ProcessForm", "Home", FormMethod.Post))
{
<tr>
<td>
#(Html.Kendo().IntegerTextBox()
.Name("LoanID")
.Placeholder("Enter Loan ID")
)
</td>
</tr>
}
</table>
After begin form there are <tr> tags directly! Browsers like chrome and mozilla get confused in such cases. The <table> tag should be inside the form. If we look at your code, which was exactly what I had done, <table> tag was before #using Html.BeginForm.
Internet Explorer somehow understands this, but the other browsers don't.
When I did an inspect element I found that there was a form tag within each <tr> tag and it always returned FormCollection as null. Simply defining <table> within form solved my problem.
So here's how it should be:
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="~/Images/logo.gif" />
</td>
</tr>
<tr><td>
#using (Html.BeginForm("ProcessForm", "Home", FormMethod.Post))
{
<table>
<tr>
<td>
#(Html.Kendo().IntegerTextBox()
.Name("LoanID")
.Placeholder("Enter Loan ID")
)
</td>
</tr>
</table>
}
</td></tr>
</table>
I just found out what the issue is by experimneting.
The Telerik MVC widgets don't emit any FormCollection data!!!!
Only EditorFor and TextBoxFor emit these values, plus the input buttons.
What good are these widgets if I can't use the FormCollection values from them???? Especially the DropDownList where I can retrireve data and need the selected value to pass onto other methods.
(This would be better suited as comment, but I can't comment yet)
For future reference, here's a spec (W3C might have something different) for what gets submitted when a form is submitted:
http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#category-submit
You can look at whatever HTML was generated to make sure it gets submitted. You could also use something like Fiddler to look at the Http request

Html.HiddenFor causing error

When I try to add #Html.HiddenFor(#Model.ID) to my code, I get the following error when access the page:
Compiler Error Message: CS0411: The type arguments for method 'System.Web.Mvc.Html.InputExtensions.HiddenFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
I tried reading MSDN, but the documentation is awful (they don't provide a single code example in the documentation for this method.
Here is my View:
#model CustomerService.Entity.Order
#using CustomerService.Entity
#{
ViewBag.Title = "OrderDetails";
}
<h2>
OrderDetails</h2>
#using (Html.BeginForm("HandleSubmit", "Home", FormMethod.Post))
{
<table border="1">
<tr>
<td>
<b>Order #</b>
</td>
<td>
#Model.ID
</td>
</tr>
<tr>
<td>
<b>Description</b>
</td>
<td>
#Model.Description
</td>
</tr>
<tr>
<td>
<b>Salesperson Name</b>
</td>
<td>
#Model.SalespersonName
</td>
</tr>
</table>
<h3>
Line Items</h3>
<input id="btnAddLineItem" type="submit" name="AddLineItem" value="AddLineItem" />
#Html.HiddenFor(#Model.ID)
<table border="1">
<tr>
<td>
<b>Line Item ID</b>
</td>
<td>
<b>Description</b>
</td>
</tr>
#for (int i = 0; i < #Model.LineItems.Count; ++i)
{
<tr>
<td>
#Model.LineItems[i].ID
</td>
<td>
#Model.LineItems[i].Description
</td>
</tr>
}</table>
}
HiddenFor takes an expression.
#Html.HiddenFor( model => model.ID )
HiddenFor method should get an Expression as a parameter not a value:
#Html.HiddenFor(m => m.ID)
Instead of: #Html.HiddenFor(#Model.ID)
Method signature:
HiddenFor<TModel, TProperty>(HtmlHelper<TModel>,
Expression<Func<TModel, TProperty>>)
In plain text you should give an Expression that gets an "instance" of the type of your model(in this case CustomerService.Entity.Order) and returns the desired property(in this case ID)
MSDN

Why is this cart index view (Razor engine) giving me errors

It does not seem to like #{index++;} , I have tried
#{int index++}, #(index++), #(int index++;)
This code didn't throw errors when used with MVC 2.
Here's it's giving me
ambiguity warnings about index.
#model CartTest.Models.Cart
#{
ViewBag.Title = "Index";
}
<h2>Cart Index</h2>
<table width="80%" align="center">
<thead><tr>
<th align="center">Quantity</th>
<th align="left">Item</th>
<th align="right">Price</th>
<th align="right">Subtotal</th>
</tr></thead>
<tbody>
#{int index = 0;}
#foreach (var line in Model.Lines)
{
<tr>
#Html.Hidden("Lines.Index", index);
<td align="center">#Html.TextBox("Lines[" + index + "].Quantity",line.Quantity)</td>
<td align="left">#line.Product.Name</td>
<td align="right">#line.Product.Price</td>
<td align="right">#(line.Quantity * line.Product.Price)</td>
<td align="right">#Html.ActionLink("Remove", "RemoveItem", new { productId = line.Product.ProductID }, null)</td>
</tr>
#{index++;}
}
</tbody>
<tfoot>
</tfoot>
</table>
Try like this:
#{int index = 0;}
#foreach (var line in Model.Lines)
{
<tr>
...
</tr>
index++;
}
Now that's just to make the Razor compiler happy. It's not a solution I recommend. The real solution I would recommend you is to use editor templates:
<table width="80%" align="center">
<thead>
<tr>
<th align="center">Quantity</th>
<th align="left">Item</th>
<th align="right">Price</th>
<th align="right">Subtotal</th>
</tr>
</thead>
<tbody>
#Html.EditorFor(x => x.Lines)
</tbody>
<tfoot>
</tfoot>
</table>
and inside the corresponding editor template of a Line (~/Views/Shared/EditorTemplates/LineViewModel.cshtml) which will be rendered for each element of the Line collection:
#model LineViewModel
<td align="center">
#Html.TextBoxFor(x => x.Quantity)
</td>
<td align="left">
#Html.DisplayFor(x => x.Product.Name)
</td>
<td align="right">
#Html.DisplayFor(x => x.Product.Price)
</td>
<td align="right">
#Html.DisplayFor(x => x.CalculatedTotalPrice)
</td>
<td align="right">
#Html.ActionLink("Remove", "RemoveItem", new { productId = Model.Product.ProductID }, null)
</td>
See, no more ugly loops, weakly typed helpers, dealing with some indexes, etc... Everything works by conventions.

Resources