I am re-opening my question as it has been set as duplicate while it is not - or people who tagged it as duplicate should explain me why it is a duplicate..........
https://stackoverflow.com/questions/13227988/html-displayfor-result
How can I get the result of the method Html.DisplayFor() in a C# Class, like in a View model or even in a Controller ? And not in the View Aspx or Razor.
[Edit]
In fact I have a table to display and depending on the number of record I use a Telerik table or a simple HTLM table.
For the moment I have a function in my view to get the string to display for each column so I use the same format for both tables.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ViewModels.OrderViewModel>" %>
<script runat="server" type="text/C#">
public string GetCellValue (String columnName, Order order)
{
string value = "";
switch (columnName)
{
case "Ref":
value = order.order.Reference.ToString(); break;
case "Etc":
value = Html.DisplayFor(p => order.order.Etc).ToHtmlString();break;
case "Payment date":
foreach (Executions ex in order.executions)
{
value += ex.Date.Date.ToString("yyyy-MM-dd") + " ";
}
break;
I want to move this function out of my view in the ViewModel for example, but I do not know how I can call the function Html.DisplayFor() out of a view.
Don't understand why would you want to do it, but...
using System.Web.Mvc;
using System.Web.Mvc.Html;
class Example {
void Method()
{
HtmlHelper<TModel> Html = new HtmlHelper<TModel>();
MvcHtmlString result = Html.DisplayFor(prop => Model.Prop);
}
}
After your edit, if you move GetCellValue to another place, maybe you will only need to do
MvcHtmlString result = new MvcHtmlString(order.order.Etc);
as, it should only display its value as string (unless you have set up a template for it).
Related
When I get a list of my recipes from the API to the MVC, I have a some columns like totalTimeUnitId that have integer values instead of their actual unit(grams, kg, etc.). I am trying to figure out how to write code so that instead of 1, my view will return, for example 'g'.
I have little to no experience at all in working with views and I could not figure out a way to accomplish this.
<td>
#Html.DisplayFor(modelItem => item.recipeIngredientUnitId)
</td>
For example in the code above, I would suppose that I need an #if clause that checks if item.recipeIngredientUnitId is 1, then if it is 2 and so on and it will eventually display the right unit. However, the syntax is quite an impediment for me and a little help will be very much appreciated.
Try the following:
To connect your model and the View:
In the View (.cshtml) file
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers // imports tag helpers
#model Recipe //this way you import your model to view
//then use the property of this model to display `totalTimeUnitId`
<td>
#Model.totalTimeUnitId
</td>
In Controller class
public IActionResult SomeName()
{
Recipe r = new Recipe();
return View(r); //you need to pass an instance of Recipe type
}
#Pete's code helped me out.
I added this in my Model class:
private int _totalTimeUnitId;
public int TotalTimeUnitId
{
get
{
return _totalTimeUnitId;
}
set
{
_totalTimeUnitId = value;
switch (_totalTimeUnitId)
{
case 1:
TotalTimeUnit = "min";
break;
case 2:
TotalTimeUnit = "hour(s)";
break;
default:
TotalTimeUnit = string.Empty;
break;
}
}
}
Here is my logic in a code snippet.
I am trying to login, if data comes from web-page and if it matches with the database to proceed allowing to login
[HttpPost]//post method
public ActionResult Index(FormCollection collection)//using formcollection
{
var logindata = amcs.Logins.Where(a => a.Admin_Email_Id == collection["Admin_Email_Id"] && a.Admin_Password == collection["Admin_Password"]).SingleOrDefault();//compare string
if (logindata == null)//match data
{
return Redirect("/Contract/Login/index");//redirect if not match
}
else
{
Session["Emailids"] = collection["EmailId"];//add session
Session["Passwords"] = collection["AdminPassword"];
return Redirect("/Contract/Homepage/index");
}
}
If you are getting NULL as a result, have you looked further into this yourself?
For example, what values are
collection["Admin_Email_Id"]
collection["Admin_Password"]
Does the data in amcs.Logins contain objects whose properties match those values? You can hover the mouse of the data and look at it in the debugger.
EDIT
In response to a comment:
In the HTML does the
<input type="text" id="Admin_Email_Id"> also have an attribute name="Admin_Email_Id"? If not then add it manually e.g.
Html.TextBoxFor(m => m.Admin_Email_Id, new { name = "Admin_Email_Id", PlaceHolder = "EmailId"})
I'd be surprised that you need to do that though, but it's worth checking the HTML to check that name is there. Without name, when posting to the controller, the FormColleciton won't have a value for that missing name
I am creating column model at code behind, but I am stack at creating editoption for numeric values which is a function checks the value if its numeric otherwhise alert a message but I couldn't fit javascript function at code behind.
after I model at code behind I convert to json to use at in aspx page.
c# code behind
else if (prop.PropertyType == typeof(decimal))
{
pr.name = prop.Name;
pr.index = prop.Name;
pr.sorttype = "number";
pr.editoptions = new { dataInit = numericonly };
}
aspx
function numericonly(elem) {
$(elem).numeric(false, function() { alert("Integers only"); this.value = ""; this.focus(); });
}
The problem is clear. JSON don't support functions as a type. What you easy can do is the following: 1) you fill strings as the value of dataInit on the server side. 2) you "pre-process" the column model and change illegal string values of dataInit to the reference to the corresponding function. You can "pre-process" the column model before creating of the grid or after creating inside of beforeProcessing callback or even later somewhere before starting of editing. Because dataInit will be used only during editing you have to fix dataInit at any time before the editing will be started.
To change colModel you can either use setColProp method or you can get the reference of internal colModel array by var colModel = $("#gridid").jqGrid("getGridParam", "colModel"); and then do any required modification of some columns. The code will look about as below:
function numericonly(elem) {
...
}
...
var colModel = $("#gridid").jqGrid("getGridParam", "colModel"), i, cm;
for (i = 0; i < colModel.length; i++) {
cm = colModel[i];
if (cm.editoptions != null && typeof cm.editoptions.dataInit === "string") {
switch (cm.editoptions.dataInit) {
case "numericonly":
// function numericonly is visible here and can be used
cm.editoptions.dataInit = numericonly;
break;
....
default:
delete cm.editoptions.dataInit; // delete wrong value
break;
}
}
}
The old answer contains description of the same idea for the case of custom formatters.
I'm passing a List to an MVC view and generating checkboxes for each object in the list (The checkboxes are named t.Name).
I'd like to be able to tell which checkboxes were checked once the form is posted. However, I'd like to avoid using the FormCollection object. Is there any way to do this?
Set the name of your checkboxes to something like "MyObject[" + index + "].Checked", and for each checkbox also put a hidden input field named something like "MyObject[" + index + "].Name" with the value set to t.Name.
If you name your fields like that, the default model binder can take your form values and map them to a list of objects with a Name property and a Checked property.
I would try something like the following:
<% foreach(var t in Model)
{ %>
<div>
<%= Html.Hidden("MyObject[" + index + "].Name", t.Name, new { id = "MyObject_" + index + "_Name" }) %>
<%= Html.Checkbox("MyObject[" + index + "].Checked", false, new { id = "MyObject_" + index + "_Checked" }) %>
</div><%
} %>
I use the anonymous type with id property so that the MVC framework components don't generate HTML elements with invalid id values, but it isn't really necessary.
Your action handling the post would look something like this:
[HttpPost]
ActionResult MyAction(IList<MyObject> objects)
{
foreach (MyObject obj in objects)
{
if (obj.Checked)
{
// ...
}
else
{
// ...
}
}
return View();
}
I'm trying to set up a page where I display a list of items and the details of the selected item. I have it working but wonder whether I have followed the correct approach. I'll use customers as an example
I have set the aspx page to inherit from an IEnumerable of Customers. This seems to be the standard approach to display the list of items. For the Details I have added a Customer user control which inherits from customer.
I think i'm on the right track so far but I was a bit confused as to where I should store the id of the customer whose details I intend to display. I wanted to make the id optional in the controller action so that the page could be hit using "/customers" or "customers/1" so I made the arg optional and stored the id in the ViewData like this:
public ActionResult Customers(string id = "0")
{
Models.DBContext db = new Models.DBContext();
var cList = db.Customers.OrderByDescending(c => c.CustomerNumber);
if (id == "0")
{
ViewData["CustomerNumber"] = cList.First().CustomerNumber.ToString();
}
else
{
ViewData["CustomerNumber"] = id;
}
return View("Customers", cList);
}
I then rendered the User control using RenderPartial in the front end:
<%var CustomerList = from x in Model
where x.CustomerNumber == Convert.ToInt32(ViewData["CustomerNumber"])
select x;
Customer c = (Customer)CustomerList.First(); %>
<% Html.RenderPartial("Customer",c); %>
Then I just have an actionLink on each listed item:
<%: Html.ActionLink("Select", "Customers", new { id = item.CustomerNumber })%>
It all seems to work but as MVC is new to me I would just be interested in others thoughts on whether this is a good approach?
In regards to proper MVC and separations of concerns, you shouldn't be calling LINQ queries in your view. To get around that, change your controller action code from what you have to this:
if (id == "0")
{
ViewData["CustomerDetails"] = cList.First();
}
else
{
ViewData["CustomerDetails"] = From x in db.customers where x.id = cInt(id);
}
then your partial
<% Html.RenderPartial("Customer",ViewData["CustomerDetails"]); %>
Are you showing the customer information on the same screen that you have your list of customers and not a separate view?
In this case I would take the following approach.
Display a list of customer's, be it a listbox or drop down list.
Let's assume it's a drop down list, probably not very user friendly
You would have the text as the customer name and then the value as the customer id
<select title="Customers">
<option label="Pieter" value="001"></option>
</select>
and using JQuery's $.getJSON you could load the new data via a call to an asp.net MVC action.
Note that your Action should return JsonResult