how can I fetch the value in html file I used entity framework - asp.net-mvc

I wrote this below code on controller section
DateTime start = student.Timestamp;
for (int i = 0; i < 1000; i++)
{
}
DateTime end = student.Endstamp;
How can I fetch the value start and end Variable in the cshtml file(text box) ?
Please note that I am using in Entity Framework.

You can use viewbag to get values from a controller to view. e.g:
In controller
Public ActionResult Index(){
...
ViewBag.start = student.Timestamp;
for (int i = 0; i < 1000; i++)
{
//your code
}
ViewBag.end = student.Endstamp;
...
return View();
}
In View index.cshtml
<input type="text" id="txtStart" value="#ViewBag.start" />
<input type="text" id="txtEnd" value="#ViewBag.end" />
or
<p>this is start: #ViewBag.start</p>
<p>this is end: #ViewBag.End</p>

Related

MVC Map array in model for passing model to controller

I have form with several input buttons. Within this forms buttons can do actions. With 1st button I generate table(object with property of type int[,]). With the 2nd button I am going to do smth with this object. The first is ok, the 2nd returns null for model to controller.
How to pass from form this object with array inside to controller? Now in SubmitForm method I have value for buttonType, but matrix is null(should be data from table).Appreciate any help
Model
public class Matrix
{
public int[,] Data { get; set; }
}
Controller
[HttpPost]
public ActionResult SubmitForm(Matrix matrix, string ButtonType) - matrix is NULL here, how to get info from form
{
if (ButtonType == "Rotate")
{
return RotateMatrix(matrix);
}
//other code
}
[HttpPost]
public ActionResult RotateMatrix(Matrix matrix)
{
//-some code
return PartialView("_MatrixView", matrix);
}
View
#model Project.Models.Matrix
#{
ViewBag.Title = "Home Page";
var options = new AjaxOptions()
{
UpdateTargetId = "Matrix",
};
}
#using (Ajax.BeginForm("SubmitForm", "Home", FormMethod.Post, options))
{
<div id="Matrix"></div>
<input type="submit" value="Rotate" name="ButtonType" />
<input type="submit" value="Generate" name="ButtonType"/>
}
PartialView
#model Project.Models.Matrix
<table>
#for (int column = 0; column < Model.Data.GetLength(0); column++)
{
<tr>
#for (int row = 0; row < Model.Data.GetLength(1); row++)
{
var item = Model.Data[column, row];
<td>#Html.DisplayFor(m => item)</td>
}
</tr>
}
</table>

how to insert multiple row in form method using for loop in asp.net mvc

i am written the code for CREATE Operation in view which will insert multiple of rows in database using form-tag with for-loop. when click on Create button it will save only one row so i want that when i click on button no.of row should be created.
here code for View..
#model CarParking.Models.Area
#for (int i = 1; i <= Model.NoOfParkingPlaces; i++)
{
using (Html.BeginForm("Create", "ParkingPlace", FormMethod.Post))
{
<label>AreaID:</label>
<input id="AreaID" name="AreaID" type="text" value="#Model.AreaID" />
<label for="Parking_IDs">Parking IDs</label>
<input type="text" value="P.Id: #i" name="PlaceId" />
<input type="submit" value="Create" />
}
}
here code for Controller...
public ActionResult Create(string areaName)
{
Area area = db.Areas.SingleOrDefault(x => x.ParkingPlaceName == areaName);
return View(area);
}
[HttpPost]
public ActionResult Create([Bind(Include = "ParkID,PlaceId,CarID,AreaID")] ParkingPlace parkingPlace)
{
if (ModelState.IsValid)
{
db.ParkingPlaces.Add(parkingPlace);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(parkingPlace);
}
Here some images how my View looksenter image description here
Are you saying you want to post ALL the forms on the page at once?
If so - it doesn't work like that... One option would be to use javascript to AJAX post them all, but the correct way to do it is to use one form, with each of the ParkingPlaces in it.
This article goes through it in detail: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
#for( int i = 0; i < Model.NoOfParkingPlaces; ++i)
{
#Html.EditorFor(m => m.ParkingPlaces[i].AreaId)
#Html.EditorFor(m => m.ParkingPlaces[i].Id)
... etc
}
and your action parameters become;
public ActionResult Create(IEnumerable<ParkingPlace> ParkingPlaces)
{

For loop issue in razor

I am working on asp.net mvc4 and i am using razor for displaying data in my view.I am using one for loop in my view.my loop code is like below.
**#for (int i = 0; i < 5; i++)
{
if (i<(#Html.DisplayFor(m => m.ProductInfo[5].Value)))
{
<img src="../../Images/star-on.png" />
}
else
{
<img src="../../Images/star-off.png" />
}
}**
In my above for loop in if condition i am trying to bind the number like 4.But it gives error like below
operator ' ' cannot be applied to operands of type 'int' and 'system.web.mvc.mvchtmlstring'
But when i display this razor code in my view like its showing the number "4".The code is like below.
#Html.DisplayFor(m => m.ProductInfo[5].Value)
You need to check against the value not the display for the value
#for (int i = 0; i < 5; i++)
{
if (i < Model.ProductInfo[5].Value) #* <-- This line changed *#
{
<img src="../../Images/star-on.png" />
}
else
{
<img src="../../Images/star-off.png" />
}
}
Update
If your Model.ProductInfo[5].Value is of type string you need to do the following (providing you are not willing to change Value's type)
#{
int productFiveValue;
bool canConvert = Int32.TryParse(Model.ProductInfo[5].Value, out productFiveValue);
}
#for (int i = 0; i < 5; i++)
{
if (canConvert && i < productFiveValue)
{
<img src="../../Images/star-on.png" />
}
else
{
<img src="../../Images/star-off.png" />
}
}
You don't need an HTML helper here, they usually return MvcHtmlString instances and you can't compare them to numbers. This should work:
if (i < Model.ProductInfo[5].Value)

Element naming convention in Razor generator within a foreach loop

I'm trying to generate element names using Html.NameFor<> method, here's my code:
#foreach (var category in Model.Categories)
{
<input type="hidden" name="#Html.NameFor(m=> category.CategoryId)"
value="#category.CategoryId" />
}
The generated item's name get this value: category.CategoryId, instead of Categories[i].CategoryId (where i refers to the current indexer).
Why isn't it working?
in short, use a for loop instead of a foreach loop (see the answer here). You need to manually index it
MVC Razor view nested foreach's model
EDIT: added sample code
#for(int i=0; i < Model.ListTwo.Count; i++)
{
#Html.HiddenFor(t => t.ListTwo[i].Id)
}
Okay, for collections that inherit from ICollection, try
#for (int i = 0; i < Model.CollectionThree.Count; i++)
{
#Html.Hidden("CollectionThree[" + i + "].Id", Model.CollectionThree.ElementAt(i).Id)
}
Another edit:
To avoid using the property name, you could do something like
#for (int i = 0; i < Model.CollectionThree.Count; i++)
{
#Html.Hidden(Html.NameFor(t => Model.CollectionThree) + "[" + i + "]." +
Html.NameFor(t =>Model.CollectionThree.ElementAt(i).Id)
,Model.CollectionThree.ElementAt(i).Id )
}
Its inelegant, but it doesn't hardcode the property name.
And then lets take those guys out of the loop
#{
var collectionname = Html.NameFor(t => Model.CollectionThree);
var propname = Html.NameFor(t => Model.CollectionThree.First().Id);
}
#for (int i = 0; i < Model.CollectionThree.Count; i++)
{
#Html.Hidden( collectionname+ "[" + i + "]." + propname ,Model.CollectionThree.ElementAt(i).Id )
}
My apologies for not responding earlier. I logged out as I had other things to do. You also may want to do a null check ie, if count > 0, then assign the propname, otherwise skip the whole thing
According to user1778606's answer, I will use the prop. name and indexer separately, like this:
#{
var modelName = Html.NameFor(m => m.Categories);
var catIndex = 0;
}
#foreach (var category in Model.Categories)
{
<input type="hidden" class="checkbox"
name="#string.Format("{0}[{1}]", modelName, catIndex++)"
value="#category.CategoryId" />
}
Use #Html.HiddenFor and pass in the array indexed expression for CategoryId
#for(int i=0; i < Model.Categories.Count; i++)
{
#Html.HiddenFor(m => Model.Categories[i].CategoryId)
}

send a ViewModel which contains a list with a Html.BeginForm (MVC 4)

My viewmodel contains a integer list, the problem I have is that when I send my modified form viewmodel, it is always equal to null.
My ViewModel :
public class testViewModel
{
public List<int> itemTest { get; set;
}
Action in my Controller :
For example, I'll try to sum ​​the new values ​​entered into the form, but the sum calculated is always equal to 0, nothing changes.
public ActionResult form(int nbre)
{
testViewModel montest = new testViewModel()
{
itemTest = new List<int>()
};
for(int i=0;i<nbre ;i++)
{
montest.itemTest.Add(0);
}
return View(montest);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult form(testViewModel maListe)
{
int somme = 0;
if (maListe.itemTest != null)
{
if (maListe.itemTest.Count() != 0)
{
foreach (var item in maListe.itemTest)
{
somme += item;
}
}
}
//listtest = maListe;
return RedirectToAction("test2", new { qte = somme });
}
My view
#model MvcWebRole1.ViewModels.testViewModel
#{
ViewBag.Title = "Formulaire";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table>
#foreach (var item in Model.itemTest)
{
<tr >
<td >
#Html.Label("Quantitée")
</td>
<td>
#Html.EditorFor(model => item)
#Html.ValidationMessageFor(model => item)
</td>
</tr>
}
</table>
<input type="submit" value="Valider" />
}
Thank you kindly help me
You need to index each item in your collection. The issue with your code seems to be the use of foreach. You really want to use for instead and pass in the index with the EditorFor call.
for (int i = 0; i < Model.Items.Count; i++) {
#Html.EditorFor(m => m.Items[i])
}
This only works for ordered lists that will never change their order. If you want to reorder items I suggest your read Phil Haack's great post on sending lists to the server.
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
list binding
<form>
#for(int i=0;i<Model.itemTest.Count ;i++)
{
#Html.TextBoxFor(x=>x.itemTest[i])
//or just <input type="text" name="itemTest "/> working to
}
for(int i=0;i<nbre ;i++)
{
montest.itemTest.Add(0);
}
return View(montest);
Looks like you are filling your int array with zeroes instead of i's. This should read montest.itemTest.Add(i); .

Resources