i am trying to send integer value from controller to view and display in view multiplied by 0.2
here the code in controller
public ActionResult Details()
{
ViewBag["salary"] = 1400;
return View();
}
and the code in view
#{
Layout = null;
int Salary=int.Parse(#ViewBag["salary"]);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
</head>
<body>
<div>
<p> Salary: </p>
#(Salary / 0.2)
</div>
</body>
</html>
but it throw an exception
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll but was not handled in user code
Additional information: Cannot apply indexing with [] to an expression
of type 'System.Dynamic.DynamicObject'
Use this code in your controller:
ViewBag.salary = 1400;
And this code in your view:
int Salary=(int)ViewBag.salary;
Using the ViewBag is typically considered poor practice, I'd recommend using a Model (Model-View-Controller). I'll also mention that adding logic in the view is also poor practice, your logic should be controlled by the Controller.
Model
public class DetailsVM
{
public decimal Salary { get; set ; }
}
Controller (method)
public ActionResult Details()
{
var model = new DetailsVM();
model.Salary = 1400 / 0.2;
return View(model);
}
View
#model DetailsVM
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
</head>
<body>
<div>
<p> Salary: </p>
#Model.Salary
</div>
</body>
</html>
Related
My textbook says that "TempData gets destroyed immediately after it’s used in subsequent HTTP request", so I write a simple test to verify
below is my code:
// SimpleForm.cshtml is just a simple view that uses a form to send post request to ReceiveForm action method
//Result.cshtml is just a simple view that products an output
public class HomeController : Controller
{
public ViewResult Index() => View("SimpleForm");
[HttpPost]
public RedirectToActionResult ReceiveForm(string name, string city)
{
TempData["name"] = name;
TempData["city"] = city;
return RedirectToAction(nameof(Transfer));
}
public RedirectToActionResult Transfer()
{
string name = TempData["name"] as string;
string city = TempData["city"] as string;
return RedirectToAction(nameof(Data));
}
public ViewResult Data()
{
string name = TempData["name"] as string;
string city = TempData["city"] as string;
return View("Result", $"{name} lives in {city}");
}
}
so when the application runs, it goes to Index() action method first, I fill up the form with name and city and press submit button, then it goes to ReceiveForm() action method, which setup TempData and redirect to Transfer() action method.
In the Transfer() action method, I read TempData, so TempData should get destroyed and unavailable to read in the next http request according to the textbook.
But in the Data(), I find that I can still read TempData, see the screenshot below:
and I checked the chrome dev tool, there was one post request and two get requests, which is all good and correct. so when does TempData actually get destroyed ?
additional code:
SimpleForm.cshtml:
#{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Controllers and Actions</title>
<link rel="stylesheet" asp-href-include="lib/bootstrap/dist/css/*.min.css" />
</head>
<body class="m-1 p-1">
<form method="post" asp-action="ReceiveForm">
<div class="form-group">
<label for="name">Name:</label>
<input class="form-control" name="name" />
</div>
<div class="form-group">
<label for="name">City:</label>
<input class="form-control" name="city" />
</div>
<button class="btn btn-primary center-block" type="submit">Submit</button>
</form>
</body>
</html>
Result.cshtml:
#model string
#{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Controllers and Actions</title>
<link rel="stylesheet" asp-href-include="lib/bootstrap/dist/css/*.min.css" />
</head>
<body class="m-1 p-1">
Model Data: #Model
</body>
</html>
For your scenario, this is caused by RedirectToActionResult. For RedirectToActionResult, which is IKeepTempDataResult.
public class RedirectToActionResult : ActionResult, IKeepTempDataResult
SaveTempDataFilter is filter that saves temp data. It will call SaveTempData.
private static void SaveTempData(
IActionResult result,
ITempDataDictionaryFactory factory,
IList<IFilterMetadata> filters,
HttpContext httpContext)
{
var tempData = factory.GetTempData(httpContext);
for (var i = 0; i < filters.Count; i++)
{
if (filters[i] is ISaveTempDataCallback callback)
{
callback.OnTempDataSaving(tempData);
}
}
if (result is IKeepTempDataResult)
{
tempData.Keep();
}
tempData.Save();
}
For SaveTempData, it will check whether IActionResult result is IKeepTempDataResult. If it is, it will keep the tempData.
If you want to avoid keep tempData between request, you could change RedirectToAction to LocalRedirect like
public IActionResult Transfer()
{
string name = TempData["name"] as string;
string city = TempData["city"] as string;
return LocalRedirect("~/Home/Data");
//return RedirectToAction(nameof(Data));
}
I go to a View, submit data via POST, but the redirect cannot find the Controller method. What am I doing wrong here? After submitting the form I get:
404 error: cannot find page. URL is: http://localhost:52008/InternalController/UpdateCardFormPost
Snippet from InternalController.cs:
public ActionResult UpdateCardFormView()
{
var CardToUpdate = new CardView();
return View(CardToUpdate);//return implementation of Cards.cshtml with the empty model that was passed to it
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateCardFormPost(CardView c)
{
CardModelIO.WriteCard(c);//#TODO: IMPLEMENT
return View("CardDetailView", c);
}
UpdateCardFormView.cshtml (the view with the form I am submitting):
#using LeanKit.API.Client.Library.TransferObjects
#model CardView
<!DOCTYPE html>
<html>
<!--Form used to change a card
STARTING DISPLAY called by in Internal/UpdateCardFormView
ENDING DISPLAY (post) called by UpdateCardForm in InternalController a specified below-->
<head>
</head>
<body>
#Html.BeginForm("UpdateCardFormPost", "InternalController", FormMethod.Post)
#Html.TextBoxFor(c => c.AssignedUserName);
<input type="submit" value="Submit Changes" />
</body>
</html>
Heres the CardDetailView.cshtml (the view I should be redirected to):
#using LeanKit.API.Client.Library.TransferObjects
#model IEnumerable<CardView>
<!--used for displaying an individual card in detail view
referenced in UpdateCardFormPost() method of Internal controller-->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
CardView j = Model;
<p>j.AssignedUserId</p>
</body>
</html>
You've specified the controller name as InternalController but it's probably just called "Internal".
Try changing
#Html.BeginForm("UpdateCardFormPost", "InternalController", FormMethod.Post)
to
#Html.BeginForm("UpdateCardFormPost", "Internal", FormMethod.Post)
you are missing closing form tag
you should do it like
using (#Html.BeginForm("UpdateCardFormPost", "InternalController", FormMethod.Post))
{
...
}
#using(Html.BeginForm())
{
#Html.TextBoxFor(c => c.AssignedUserName);
<input type="submit" value="Submit Changes" />
}
I am new in MVC. In my case in View it gives error on else condition.Please guide me how to use it.. my View code is here
#model InputCustomer.Models.Customer
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DisplayCustomer</title>
</head>
<body>
<div>
The Customer ID is #Model.Id<br/>
The Customer Code is #Model.CustomerCode<br />
#if (Model.Amount > 100){
<%This is Privildged Customer%>
}
#else{
<% This is a normal Customer%>
}
</div>
</body>
</html>
According to how to create an else if statement in Razor? you don't need to use # before else:
#if (Model.Amount > 100) {
#:This is Privilged Customer
}
else {
#:This is a normal Customer
}
Also <% and %> has no special meaning in Razor syntax. If you want text - simply keep it as text.
It should be:
<div>
#if (Model.Amount > 100)
{
<text>This is Privildged Customer</text>
}
else{
<text>This is a normal Customer</text>
}
</div>
Do not add addition # on else statement. Only one # per if and else statement or put them inside:
#{
//TODO: Logic here
}
Lastly don't edit our post, just put a comment if you have inputs.
I am trying to get to grips with WebGrid in a c# MVC4 project. The following code gives this error...
Compiler Error Message: CS1502: The best overloaded method match for
'System.Web.Helpers.WebGrid.WebGrid(System.Collections.Generic.IEnumerable,
System.Collections.Generic.IEnumerable, string, int, bool,
bool, string, string, string, string, string, string, string)' has
some invalid arguments
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
#{
List<int> obj1 = new List<int>(){ 1, 2, 3, 4 };
var obj1_i = (IEnumerable<int>)obj1;
var grid = new WebGrid(obj1_i);
}
</head>
<body>
<div>
#grid.GetHtml()
</div>
</body>
</html>
The problem is that WebGrid expects your model to be IEnumerable<dynamic>, not IEnumerable<int>. Change your code to the following:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
#{
List<dynamic> obj1 = new List<dynamic>(){ 1, 2, 3, 4 };
var grid = new WebGrid(obj1);
}
</head>
<body>
<div>
#grid.GetHtml()
</div>
</body>
I have this simple MVC 4 code. I querying the database and getting all the results, saving then in a ViewBag object and then looping through them with a foreach but the an error:
Cannot apply indexing with [] to an expression of type
does not let me show them. What im missing?
Here the sql query with entityframework
public ActionResult Index()
{
var ReturnLabelsAndInputsForIndexations = Conexion.MainConexion;
var IndexationForm = ReturnLabelsAndInputsForIndexations.Labels.ToList();
ViewBag.IndexationForm = IndexationForm;
return View();
}
And the index View
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
#foreach (var Indexacion_Labels in ViewBag.IndexationForm)
{
<tr>
<td>#Indexacion_Labels["LABELS"]//Exception HERE</td>
<td>#GetInputType(Indexacion_Labels["INPUT_TYPE"], Indexacion_Labels["NAME"])</td>
</tr>
}
</table>
</div>
</body>
</html
The type of ReturnLabelsAndInputsForIndexations.Labels (whatever type that is) does not implement an indexer. To resolve this you would either need to add this to the view model for labels
public this[string index]
{
get
{
...
}
}
OR change your view code to something like this (assuming the properties of the view model exist)
<tr>
<td>#Indexacion_Labels.Labels</td>
<td>#GetInputType(Indexacion_Labels.Input_Type, Indexacion_Labels.Name)</td>
</tr>