How to bind new list via Html - c#

Here is my codes I just want to show on html page. I couldn't understand how to bind it. What do I have to use in HTML page inside foreach and above !DOCTYPE html.Actually I want to check that the IP Address and I want to show if it is online or not via Ping. Thanks for your help.
public class HomeController : Controller
{
private PrinterEntities db = new PrinterEntities();
public ActionResult Index()
{
List<string> catlist = new List<string>();
foreach (var item in db.C_Network)
{
if (CheckInternetConnection(item.IPAdresi))
{
catlist.Add(item.IPAdresi);
}
}
return View(catlist);
}
public bool CheckInternetConnection(string HostName)
{
bool result = false; // assume error
try
{
Ping oPing = new Ping();
PingReply reply = oPing.Send(HostName);
if (reply.Status == IPStatus.Success)
{
result = true;
}
}
catch (Exception E)
{
}
return result;
}
}
<div>
<ul>
#foreach (var item in Model)
{
#if ()
{
}
}
</ul>
</div>

I suggest:
public class HomeController : Controller
{
private PrinterEntities db = new PrinterEntities();
public ActionResult Index()
{
List<string> catlist = new List<string>();
foreach (var item in db.C_Network)
{
if (CheckInternetConnection(item.IPAdresi))
catlist.Add(item.IPAdresi);
}
}
ViewData["List"] = catlist;
return View();
}
You can get the list in aspx byList<string> Cats = (List<string>)ViewData["List"]; and iterate in for loop

Related

List shows empty on Razor Pages, while it is full

I'm getting some data from a API from which i create a List, however when i try to loop through the list in the .cshtml file it shows nothing and the count of the list is 0. But when i loop through the list in the OnGetAsync() method it does shows results.
I've tried it without the async on and i tried to fill the list within the getDataAsync() method.
public IList<Employee> Employee = new List<Employee>();
public async void OnGetAsync()
{
// Sets up HttpClient
await RunAsync();
// API call method which returns a list filled with the results
Employee = await GetDataAsync("api-url");
// Shows Results!
foreach (var item in Employee)
{
Debug.WriteLine(item.name);
}
}
static async Task<List<Employee>> GetDataAsync(string path)
{
string data = null;
List<Employee> list = new List<Employee>();
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync();
}
JObject json = JObject.Parse(data);
// Get the only the data i need from the entire json api result
foreach (var d in json["data"])
{
string setId;
string setName;
string setUrl;
if (d["id"] == null)
{
setId = "NA";
} else
{
setId = d["id"].ToString();
}
if (d["person"]["full_name"] == null)
{
setName = "NA";
} else
{
setName = d["person"]["full_name"].ToString();
}
if (d["avatar"]["url_small"] == null)
{
setUrl = "NA";
} else
{
setUrl = d["avatar"]["url_small"].ToString();
}
list.Add(new Employee
{
id = setId,
name = setName,
avatar_url = setUrl
});
}
Debug.Unindent();
return list;
}
<!-- Shows 0 -->
<p>#Model.Employee.Count</p>
<!-- Shows nothing -->
#foreach (var item in Model.Employee)
{
<p>#Html.DisplayFor(modelItem => item.name)</p>
}
I expect to be able to loop through the list and showing results on the webpage, instead the count for the list is on 0 and it shows nothing.
The problem in your code is that OnGetAsync is an async method, which should return a Task, while you're returning void
Just change the return type of it.
public async Task OnGetAsync()
{
// Your code here
}

Display a list from controller in the view MVC

enter image description hereI have a controller that gets its data from a user defined function using Entity framwework.I am trying to just display my data in the view and populate my table.
My Controller looks like this:
public ActionResult Index()
{
var description = "Toyota";
QuotingEngineEntities1 vehicles = new QuotingEngineEntities1();
List<object> list = new List<object>();
using (var context = new QuotingEngineEntities1())
{
var vehicle = from s in context.fn_GetVehicle(description)
select new
{
s.MAKE,
s.MODEL,
s.PRICE,
s.POWER,
s.Transmission
};
list.Add(vehicle.FirstOrDefault());
}
ViewBag.list = list;
return View(ViewBag.list);
}
AND MY View looks like this
#foreach (var v in ViewBag.list)
{
<li>#v.MODEL</li> //i get an error
<br />
}
I finally got it work.i had to loop through the data before adding it to the list.
public ActionResult Index()
{
var description = "Toyota";
List<fn_GetVehicle_Result> list = new List<fn_GetVehicle_Result>();
using (var context = new QuotingEngineEntities1())
{
var query = context.fn_GetVehicle(description);
foreach (var v in query)
{
list.Add(v);
}
ViewBag.list = list;
}
return View("Index",ViewBag.list);
}
enter code here
You are trying use Viewbag with your list data but it is not advisable way to do this and you dont have to add Viewbag into View() method. It is sent automatically into view by controller.
I would suggest to use ViewModel or ExpandoObject to send your collection into view. You can implement like following
//controller
public ActionResult Index()
{
using (var context = new QuotingEngineEntities1())
{
var vehicle = from s in context.fn_GetVehicle(description)
select new
{
s.MAKE,
s.MODEL,
s.PRICE,
s.POWER,
s.Transmission
};
dynamic yourmodel = new ExpandoObject();
yourmodel.Vehicles = vehicle.ToList();
}
return View(yourmodel);
}
// view
#using YourProject; // Your Project Name
#model dynamic
#foreach (var v in model.Vehicles)
{
<li>#v.MODEL</li>
<br />
}

Sending List from View to Controller results in null List in MVC

I'm trying to create a List of users in MVC, where there's a button to add users generated randomly and there's a delete button for each user to erase them from the list.
I send it from the Controller to the View and it generates one user. When I try to add one more, it just changes it. I guess it deletes the items in the List.
I'm trying to pass the list back to the Controller, but it doesn't work.
Can someone help please?
My Model:
public class UsersClass
{
public int Code { get; set; }
public string Name { get; set; }
public UsersClass(int Code, string Name)
{
this.Code = Code;
this.Name = Name;
}
}
My Controllers:
List<UsersClass> UsersList = new List<UsersClass>();
public ActionResult Index()
{
return View(UsersList);
}
[HttpPost]
public ActionResult AddUser(List<UsersClass> UsersList)
{
if (UsersList == null)
{
int a = 123;
UsersList = new List<UsersClass>();
}
Random generator = new Random();
string[] vez_nevek = new string[10] { "Kovács", "Szekeres", "Király", "Szabó", "Vicha", "Kozma", "Ferencz", "Pócsi", "Tinka", "Horváth" };
string[] ker_nevek = new string[10] { "Lajos", "Barnabás", "Róbert", "Balázs", "János", "Béla", "Petra", "Anna", "Ferenc", "Attila" };
string vezetek_nev = vez_nevek[generator.Next(vez_nevek.Length)];
string kereszt_nev = ker_nevek[generator.Next(ker_nevek.Length)];
UsersList.Add(new UsersClass(generator.Next(100000, 999999), vezetek_nev + " " + kereszt_nev));
return View("~/Views/UserManagement/Index.cshtml", UsersList);
}
And my View to add a user:
<h2>User Management</h2>
#using (Html.BeginForm("AddUser", "UserManagement", FormMethod.Post))
{
int index = 0;
foreach (var item in Model)
{
Html.Hidden("item[" + index + "].Code", item.Code);
Html.TextBox("item[" + index + "].Name", item.Name);
index++;
}
<input type="submit" value="Add User" />
}
Your HttpPost method AddUser doesnt know about the list. You should create a ViewModel that contains a list of users. A ViewModel is one way of communicating data between View and Controller. The user edits the model while they are on the page and when they click save/delete the HttpPost method for that controller will be called. Create a parameter in the HttpPost method that is the model. The View knows about the ViewModel and will send it to the controller. see code below.
ViewModel:
public class UserManageViewModel
{
public List<UsersClass> users {get; set;}
}
View:
the line #model UserManageViewModel is crucial for your view to have or else it wont know what to send to the controller.
#model UserManageViewModel
<h2>User Management</h2>
#using (Html.BeginForm("AddUser", "UserManagement", FormMethod.Post))
{
int index = 0;
foreach (var item in Model.users)
{
Html.Hidden("item[" + index + "].Code", item.Code);
Html.TextBox("item[" + index + "].Name", item.Name);
index++;
}
<input type="submit" value="Add User" />
}
Controller:
public ActionResult Index()
{
UserManageViewModel model = new UserManageViewModel();
model.users = new List<UsersClass>();
return View(model);
}
[HttpPost]
public ActionResult AddUser(UserManageViewModel model)
{
if (model.users.IsEmpty() || model.users == null)
{
int a = 123;
model.users = new List<UsersClass>();
}
Random generator = new Random();
string[] vez_nevek = new string[10] { "Kovács", "Szekeres", "Király", "Szabó", "Vicha", "Kozma", "Ferencz", "Pócsi", "Tinka", "Horváth" };
string[] ker_nevek = new string[10] { "Lajos", "Barnabás", "Róbert", "Balázs", "János", "Béla", "Petra", "Anna", "Ferenc", "Attila" };
string vezetek_nev = vez_nevek[generator.Next(vez_nevek.Length)];
string kereszt_nev = ker_nevek[generator.Next(ker_nevek.Length)];
model.users.Add(new UsersClass(generator.Next(100000, 999999), vezetek_nev + " " + kereszt_nev));
return View(model);
}
Hope this helps. Cheers :)
you should name all input the same same
#Html.TextBox("UsersList", item.Name);
- Action method
public ActionResult AddUser(List<string> UsersList){
}

How to pass IEnumerable<T> to View

Hello i'm newbie to MVC,
i want to display webgrid in view,I'm trying to display create and display in same page,i'm getting problem at the time of displaying data in webgrid,
This is my code:
Controller:
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
IEnumerable<Torder> model1 = GetProducts();
return View(model1);
}
public IEnumerable<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
///*Create instance of entity model*/
/*Getting data from database for user validation*/
var _objuserdetail = (from data in ntity.Torders
select data);
foreach (var item in _objuserdetail)
{
objStudent.Add(new Torder { Cid = item.Cid, Ccustomername = item.Ccustomername, Citem = item.Citem, Corderamount = (int)item.Corderamount});
}
return objStudent;
}
Just pass your IEnumerable<Torder> like List<Torder> On page you can write foreach loop and create grid
--- Example:
public class Torder
{
public int Id {get;set;}
public string Name {get;set;}
}
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
List<Torder> model1 = GetProducts();
return View(model1);
}
public List<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
// your logic
return objStudent;
}
---------
Page:
-------------
//html code
#model List<Torder>
#foreach(Torder order in Model)
{
// here you can build you grid(table)
order.Name
order.Id
}
P.S In future I recommend write "clean" UI without Razor (Try learn Angular - it's really very good framework) –
It's hard to tell from code in comments, but you might just be missing the #grid.GetHtml()
The block you've shown defines the grid, but now you need to emit the HTML so something shows on the page. Put this after your #{} block right before the closing div tag.

capturing value of parameter

I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}

Categories

Resources