How to redirect to a different url using tr onlick - asp.net

I have this Razor page Userview which includes a list of students in a table
I want on clicking a row to open a URL passing the ID of selected student row. Here's what I got so far
#foreach (var student in Model._User.Students)
{
<tr onclick="location.href = '#(Url.Action("Info", new { id = student.Id }))'">
<td>Some basic info of student</td>
</tr>
}
I expect to get redirected to /Info/{id} but instead got /Useview/{id}?action=Info

You can use Url.Page :
<tr onclick="location.href = '#(Url.Page("Info", new { id = 1 }))'">
Then if you have another page named Info , you can get the parameter :
#page "{id}"
#model RAZOR.Pages.InfoModel
#{
ViewData["Title"] = "Info";
}
<p>The Id is #Model.Id</p>
Info.cshtml.cs:
public class InfoModel : PageModel
{
public int Id { get; set; }
public void OnGet(int id)
{
Id = id;
}
}

Related

How to take value from Select/Option and inserted into href

I need help if it is possible. I have a list of classrooms, as it is in the picture below. I want to list all teachers in the "select option" and when the user selects the teacher he can click save and the classroom will be updated, as it is in the href. How can I take the value after the foreach loop?
<select id="teachers">
#foreach(var teacher in #Model.Teachers){
<option value="#teacher.Id">#teacher.Id</option>
}
</select>
<a asp-controller="Classroom" asp-action="Update" asp-route-teacherId=""></a>
<a asp-controller="Classroom" asp-action="Update" asp-route-teacherId="XX">Save</a>
First, for the above a tag helper, the generated HTML like this:
Save
or
Save
Besides, to update teachers in specific classrooms, you should also submit the classroom id to the Update action method, so, the generated URL should have multiple parameters(teacherid and classroomId), like this: Save
More detail information, see Anchor Tag Helper.
I have a list of classrooms, as it is in the picture below. I want to
list all teachers in the "select option" and when the user selects the
teacher he can click save and the classroom will be updated, as it is
in the href. How can I take the value after the foreach loop?
From your description, each classroom (row) should have a <select> element to choose the teacher and a "Save" button to update the current row update, right?
In this scenario, you could use the select element's change event to get the selected value, and then update the <a> tag href attribute.
You can refer the following sample:
Model:
public class ClassRoom
{
public int ID { get; set; }
public string Classroom { get; set; }
public string SubJect { get; set; }
public string Teacher { get; set; }
public DateTime Date { get; set; }
}
public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Subject
{
public int Id { get; set; }
public string SubjectName { get; set; }
}
public class ClassRoomViewModel
{
public List<ClassRoom> ClassRooms { get; set; }
public List<Teacher> Teachers { get; set; }
public List<Subject> Subjects { get; set; }
}
Controller:
public class ClassRoomController : Controller
{
public IActionResult Index()
{
// you could query the database to get the data. The following is the test data.
var viewmodel = new ClassRoomViewModel();
viewmodel.ClassRooms = new List<ClassRoom>()
{
new ClassRoom(){ ID=1, Classroom="EOIS1", Date=DateTime.Now },
new ClassRoom(){ ID=2, Classroom="EOIS2", Date=DateTime.Now }
};
viewmodel.Teachers = new List<Teacher>()
{
new Teacher(){ Id=101, Name="Tom"},
new Teacher(){ Id=102, Name="Jack"}
};
return View(viewmodel);
}
public IActionResult Update(int teacherId, int classroomid)
{
//update the classroom
//redirect to the Index page and refresh the page.
return RedirectToAction(nameof(Index));
}
}
View Page:
#model MVCWebApplication.Models.ClassRoomViewModel
<table class="table" id="customers" >
<thead>
...
</thead>
<tbody>
#foreach (var item in Model.ClassRooms) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Classroom)
</td>
<td>
#Html.DisplayFor(modelItem => item.SubJect)
</td>
<td>
<select id="teachers" class="teachers">
<option value="0">select teacher</option>
#foreach (var teacher in #Model.Teachers)
{
<option value="#teacher.Id">#teacher.Name</option>
}
</select>
</td>
<td>
<a asp-controller="ClassRoom" asp-action="Update" asp-route-classroomid="#item.ID" asp-route-teacherId="">Save</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
</tr>
}
</tbody>
</table>
#section Scripts{
<script>
$(function () {
$(".teachers").each(function (Index, item) {
$(item).change(function () {
var teacherid = $(this).val(); //get the selected value.
var existinghref = $(item).parent().parent().find("a").attr("href"); //get the hyperlink href attribute.
if (teacherid != 0) {
existinghref = existinghref + "&teacherId=" + teacherid; //add the parameter at the end of the request url.
$(item).parent().parent().find("a").attr("href", existinghref); //update the hyperlink href attribute.
}
else {
alert("Please select teacher"); //show prompt to let user select teacher.
}
});
});
});
</script>
}
The result as below:

.net MVC passing linq data from controller to view

I am trying to pass data from controller to view. I have searched the web but could not find a solution.
if I do this it works:
Controller:
var yyy = (from a in Connection.Db.Authorities select a) ;
ViewBag.data = yyy;
View:
#foreach(var item in ViewBag.data)
{
#item.Value
}
But the following code does not work:
Controller:
var yyy = (from a in Connection.Db.Authorities select new {Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)}) ;
ViewBag.data = yyy;
View:
#foreach(var item in ViewBag.data)
{
#item.Value
}
It gives "item does not contain a definition for Value" for the view file.
Any help would be great.
Thank you.
-edited: updated the second controller linq query. and corrected the first controller linq query.
It's because You already select Value and Value has no such property as Value. You should change in controller:
var yyy = (from a in Connection.Db.Authorities select a.Value); to
var yyy = (from a in Connection.Db.Authorities select a);
OR change the view to
#foreach(var item in ViewBag.data)
{
#item
}
//////////////////////////////////////////////// EDITS ////////////////////////////////////////////////
Than You should not use anonymous object. You should create ViewModelClass. For Example:
public class AuthoritiesViewModel
{
public string Value { get; set; }
public string TypeCode { get; set; }
public string Return { get; set; }
}
And change your controller:
var yyy = (from a in Connection.Db.Authorities select new AuthoritiesViewModel{ Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)});
ViewBag.data = yyy;
and in your view you will be able to use:
<table>
<tr>
<th>Value</th>
<th>TypeCode</th>
<th>Return</th>
</tr>
#foreach(AuthoritiesViewModel item in ViewBag.data)
{
<tr>
<td>#item.Value<td>
<td>#item.TypeCode<td>
<td>#item.Return<td>
</tr>
}
</table>
Also, I have a question to You. Why do You use ViewBag to pass data from controller to view? Why don't You use Model to pass these data to view according to MVC pattern?
//////////////////////////////////////////////// MORE EDITS ////////////////////////////////////////////////
To send more than one query result You can create more complex model. For example:
public class AuthoritiesViewModel
{
public string Value { get; set; }
public string TypeCode { get; set; }
public string Return { get; set; }
}
public class AnotherQueryViewModel
{
public string AnotherQueryValue { get; set; }
public string AnotherQueryTypeCode { get; set; }
public string AnotherQueryReturn { get; set; }
}
public class ModelClass
{
IEnumerable<AuthoritiesViewModel> Authorities { get; set; }
IEnumerable<AnotherQueryViewModel> AnotherQueryResults { get; set; }
}
And change the controller:
var yyy = (from a in Connection.Db.Authorities select new AuthoritiesViewModel{ Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)});
// do your another select
var zzz = (from smthing select new AnotherQueryViewModel ...)
// create model instance
ModelClass model = new ModelClass()
{
Authorities = yyy.AsEnumerable(),
AnotherQueryResults = zzz..AsEnumerable()
}
// return view with model
return View("view", model);
and in view you can use:
#model ModelClass
#*display first query result*#
<table>
<tr>
<th>Value</th>
<th>TypeCode</th>
<th>Return</th>
</tr>
#foreach(AuthoritiesViewModel item in Model.Authorities)
{
<tr>
<td>#item.Value<td>
<td>#item.TypeCode<td>
<td>#item.Return<td>
</tr>
}
</table>
#*display second query result*#
<table>
<tr>
<th>Another Query Value</th>
<th>Another Query TypeCode</th>
<th>Another Query Return</th>
</tr>
#foreach(AnotherQueryViewModel item in Model.AnotherQueryResults)
{
<tr>
<td>#item.AnotherQueryValue<td>
<td>#item.AnotherQueryTypeCode<td>
<td>#item.AnotherQueryReturn<td>
</tr>
}
</table>
use sth like this
ViewBag.qualification = new SelectList(db.Lookups.Where(x => x.lookup_type == "Qualification"), "lookup_content", "lookup_content");

Issue with a single razor view accessing two models (ASP.NET MVC3)

View(Index.chtml) is returning 0 rows while accessing two models in the view. Please see the code below. I am new to ASP.NET and I am still learning. I tried to debug and I see the table data is not being passed to correctly. Please help
================================================================================
Controller: (OrganizationCodesController.cs)
================================================================================
namespace MvcProject.Controllers
{
public class OrganizationCodesController : Controller
{
//
// GET: /OrganizationCodes/
public ActionResult Index()
{
List<TABLE_CODES> temp_codes = new List<TABLE_CODES>();
List<TABLE_ORGANIZATIONS> temp_organizations = new List<TABLE_ORGANIZATIONS>();
var viewModel = new OrganizationCodesModel(temp_codes, temp_organizations);
return View(viewModel);
}
}
============================================================================
Model: (OrganizationCodesModel.cs)
============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
namespace MvcProject.Models
{
public class OrganizationCodesModel
{
public List<TABLE_CODES> TABLE_CODES { get; set; }
public List<TABLE_ORGANIZATIONS> TABLE_CODES { get; set; }
public OrganizationCodesModel(List<TABLE_CODES> _codes, List<TABLE_ORGANIZATIONS> _organizations)
{
TABLE_CODES = _codes;
TABLE_ORGANIZATIONS = _organizations;
}
}
}
========================================================================
View: (Index.chtml)
========================================================================
#model MvcProject.Models.OrganizationCodesModel
<table>
<thead>
<tr>
<th>
ORGANIZATION_NAME
</th>
<th>
RANK
</th>
<th>
LEVEL
</th>
</thead>
<tbody>
#foreach (var item in Model.TABLE_CODES) {
<tr>
<td>
#foreach (var item_1 in Model.TABLE_ORGANIZATIONS)
{
if (item.LOCATION == item_1.ID)
{
#item1.NAME
break;
}
}
</td>
<td>
#item.RANK
</td>
<td>
#item.LEVEL
</td>
</tr>
}
</tbody>
</table>
List<TABLE_CODES> temp_codes = new List<TABLE_CODES>();
List<TABLE_ORGANIZATIONS> temp_organizations = new List<TABLE_ORGANIZATIONS>();
var viewModel = new OrganizationCodesModel(temp_codes, temp_organizations);
your instanciating two empty lists...
you should put something in your lists !
something like
List<TABLE_CODES> temp_codes = GetTempCodesFromSomewhere();
or
List<TABLE_CODES> temp_codes = new List<TABLE_CODES> {
new TABLE_CODES {LOCATION = 1, RANK = 1, LEVEL =1},
new TABLE_CODES{LOCATION = 2, RANK = 3, LEVEL = 12345}
};
Modiy your Model Class like this:
public class OrganizationCodesModel
{
public List<TABLE_CODES> listTABLE_CODES { get; set; }
public List<TABLE_ORGANIZATIONS> listTABLE_ORGANIZATIONS { get; set; }
}
I have also added text "list" as prefix to the name of the list to distinguish it from the class name otherwise both list name and class name are same.
Ok Now you have to also modify your Index action method like this:
public ActionResult Index()
{
OrganizationCodesModel model = new OrganizationCodesModel();
List<TABLE_CODES>listCodes = new List<TABLE_CODES> {
new TABLE_CODES {LOCATION = 1, RANK = 1, LEVEL =1},
new TABLE_CODES{LOCATION = 2, RANK = 3, LEVEL = 12345}
};
List<TABLE_ORGANIZATIONS> listOrganisation = new List<TABLE_ORGANIZATIONS> {
new TABLE_ORGANIZATIONS {ID = 1,NAME="ABC"},
new TABLE_ORGANIZATIONS{ID = 2,NAME="XYZ"}
};
model.ListTABLE_CODES = listCodes;
model.ListTABLE_ORGANIZATIONS = listOrganisation;
return View(model);
}
and in your View just replace your List name like this:
#foreach (var item in Model.listTABLE_CODES )
#foreach (var item_1 in Model.listTABLE_ORGANIZATIONS )
That is all. Now you will be able to see your output like this:

Pass a model to an MVCMailer view

I have a controller, which passes a model (ovw.ToList()) to a view:
//
// GET: /Clinic/Overview/
public ActionResult Overview()
{
IEnumerable<Clinic> ovw = from c in db.Clinics
select c;
return View(ovw.ToList());
}
View:
#model IEnumerable<ttp.Models.Clinic>
#foreach (var item in Model)
{
<div>#item.ClinicName</div>
#foreach (var item2 in item.Properties)
{
<div>#item2.Address</div>
This works absolutely fine on screen.
When using MVCMailer, however , if I want to display the same layout in the email, how do I pass the ovw.ToList() to the mailer view, so that I can reference the same model in this way:
(I'm stuck on what to put in as the first line in the view):
#model IEnumerable<ttp.Models.Clinic>
#foreach (var item in Model)
Thanks for any help,
Mark
You should find your answer in the 'Pass Data to Mailer Views' part of this guide: https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
To pass your model along with the view to MVCMailer, you need to use ViewData:
var comment = new Comment {From = me, To = you, Message = "Great Work!"};
ViewData = new ViewDataDictionary(comment);
In my project i doing like this it's below
i am showing all my category list in my index view
in my model class
public List<CategoryDetails> CategoryData { get; set; }
and i am also create CategoryDetails class and create a property to all my field
like this
public int CatID { get; set; }
[Required(ErrorMessage = "Enter Category Name")]
public string CatName { get; set; }
public string CatImage { get; set; }
and create a function in my main model class like this
public void LoadCategory()
{
CategoryData = (from con in dbData.Categorys
select new CategoryDetails()
{
CatID = con.CatID,
CatName = con.CatName,
CatImage = con.CatImage,
}).ToList();
}
In my controller i create a action like this
create my model class object and pass my model function to action
public ActionResult Index()
{
CategoryModel categorymodel = new CategoryModel();
categorymodel.LoadCategory();
return View(categorymodel);
}
and in my view
#model PMS.Models.CategoryModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Category Name
</th>
<th>
</th>
</tr>
#foreach (var item in Model.CategoryData)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CatName)
</td>
</tr>
}
</table>
i think this will help you

The model item is of type CookMeIndexViewModel, but requires a model item of type IEnumerable<CookMeIndexViewModel>

I am following along with the music store example to try learn ASP.NET MVC. I'm creating a cookbook application.
I have created my viewmodel that looks like this:
namespace CookMe_MVC.ViewModels
{
public class CookMeIndexViewModel
{
public int NumberOfReceipes { get; set; }
public List<string> ReceipeName { get; set; }
}
}
my controller looks like this
public ActionResult Index()
{
var meals= new List<string> { "Dinner 1", "Dinner 2", "3rd not sure" };
//create the view model
var viewModel = new CookMeIndexViewModel
{
NumberOfReceipes = meals.Count(),
ReceipeName = meals
};
return View(viewModel);
}
Finally my view looks like this
#model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
Meals
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
#item.ReceipeName
</td>
</tr>
}
</table>
I get this error.
The model item passed into the dictionary is of type CookMeIndexViewModel, but this dictionary requires a model item of type IEnumerable<CookMeIndexViewModel>.
I have followed the example. I can't see what I am doing wrong. Should I be returning my viewmodel as a generic list?
In your view you are using #model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel> which indicates that the model expected by the View is of type IEnumerable of CookMeIndexViewModel.
However in the controller you are passing an object of type CookMeIndexViewModel as a model return View(viewModel); hence the error.
Either change the view to have #model CookMe_MVC.ViewModels.CookMeIndexViewModel
or pass a IEnumerable of CookMeIndexViewModel as model to the view in controller as given below:
public ActionResult Index()
{
var meals= new List<string> { "Dinner 1", "Dinner 2", "3rd not sure" };
//create the view model
var viewModel = new CookMeIndexViewModel
{
NumberOfReceipes = meals.Count(),
ReceipeName = meals
};
List<CookMeIndexViewModel> viewModelList = new List<CookMeIndexViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList);
}
I got this message when I had a conflict between what the #model directive in the _Layout.cshtml layout view and an "inner page" view.
The _Layout.cshtml had directive..
#model MyProject.Models.MyObject
My inner page had...
#model IEnumerable<MyProject.Models.MyObject>
I was working on some test / experiment code and hit this issue when I created new controller etc. It was only when I renamed Model Object and compiled afterwards that I found the source of the problem.
Hope this helps.
Q.
in kendo ui Grid do :
public class BookBean
{
[ScaffoldColumn(false)]
public Int32 Id { set; get; }
public String Title { set; get; }
public String Author { set; get; }
public String Publisher { set; get; }
[UIHint("Integer")]
public Int32 Price { set; get; }
[UIHint("Integer")]
public Int32 Instore { set; get; }
[UIHint("Integer")]
public Int32 GroupId { get; set; }
}
in Integer.ascx in Shared/EditorTemplate folder do :
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int?>" %>
<%: Html.Kendo().IntegerTextBoxFor(m => m)
.HtmlAttributes(new { style = "width:100%" })
.Min(int.MinValue)
.Max(int.MaxValue)
%>

Resources