渚  直樹

渚 直樹

1633691220

ASP.NET MVCで ビュー内の複数のモデル

MVCでは、コントローラーから単一のビューに複数のモデルを渡すことはできません。この記事では、MVCの単一のビューで複数のモデルの回避策を提供します。

問題文

TeacherとStudentの2つのモデルがあり、教師と学生のリストを1つのビューに表示する必要があるとします。どうすればこれを行うことができますか?

以下は、TeacherクラスとStudentクラスのモデル定義です。

public class Teacher
{
    public int TeacherId { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string EnrollmentNo { get; set; }
}

以下は、すべての教師と生徒を獲得するのに役立つ方法です。

private List<Teacher> GetTeachers()
{
    List<Teacher> teachers = new List<Teacher>();
    teachers.Add(new Teacher { TeacherId = 1, Code = "TT", Name = "Tejas Trivedi" });
    teachers.Add(new Teacher { TeacherId = 2, Code = "JT", Name = "Jignesh Trivedi" });
    teachers.Add(new Teacher { TeacherId = 3, Code = "RT", Name = "Rakesh Trivedi" });
    return teachers;
}

public List<Student> GetStudents()
{
    List<Student> students = new List<Student>();
    students.Add(new Student { StudentId = 1, Code = "L0001", Name = "Amit Gupta", EnrollmentNo = "201404150001" });
    students.Add(new Student { StudentId = 2, Code = "L0002", Name = "Chetan Gujjar", EnrollmentNo = "201404150002" });
    students.Add(new Student { StudentId = 3, Code = "L0003", Name = "Bhavin Patel", EnrollmentNo = "201404150003" });
    return students;
}

必要な出力

出力

解決

1つのビューで複数のモデルを使用する方法はたくさんあります。ここでは、方法を1つずつ説明します。

1.動的モデルの使用

ExpandoObject(System.Dynamic名前空間)は、実行時にオブジェクトにプロパティを動的に追加および削除できるようにする.Net Framework4.0に追加されたクラスです。このExpandoObjectを使用して、新しいオブジェクトを作成し、教師と生徒のリストをプロパティとしてオブジェクトに追加できます。この動的に作成されたオブジェクトを、教師と生徒のビューとレンダリングのリストに渡すことができます。

コントローラコード

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to my demo!";
        dynamic mymodel = new ExpandoObject();
        mymodel.Teachers = GetTeachers();
        mymodel.Students = GetStudents();
        return View(mymodel);
    }
}

@model dynamicキーワードを使用して、モデルを動的(強く型付けされたモデルではない)として定義できます。

コードを見る  

@using MultipleModelInOneView;
@model dynamic
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>

<p><b>Teacher List</b></p>

<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model.Teachers)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>

<p><b>Student List</b></p>

<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model.Students)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

2.ビューモデルの使用

ViewModelは、複数のモデルを持つ可能性のある単一のクラスに他なりません。プロパティとして複数のモデルが含まれています。メソッドを含めることはできません。

上記の例では、2つのプロパティを持つ必要なビューモデルがあります。このViewModelは、モデルとしてビューに渡されます。ビューでインテリセンスを取得するには、強く型付けされたビューを定義する必要があります。

public class ViewModel
{
    public IEnumerable<Teacher> Teachers { get; set; }
    public IEnumerable<Student> Students { get; set; }
}

コントローラコード

public ActionResult IndexViewModel()
{
    ViewBag.Message = "Welcome to my demo!";
    ViewModel mymodel = new ViewModel();
    mymodel.Teachers = GetTeachers();
    mymodel.Students = GetStudents();
    return View(mymodel);
}

コードを見る  

@using MultipleModelInOneView;
@model ViewModel
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>

<p><b>Teacher List</b></p>

<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model.Teachers)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>

<p><b>Student List</b></p>

<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model.Students)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

3.ViewDataの使用

ViewDataは、コントローラーからビューにデータを転送するために使用されます。ViewDataは、文字列をキーとして使用してアクセスできる辞書オブジェクトです。ViewDataを使用すると、コントローラーからビューに任意のオブジェクトを渡すことができます。ビューで列挙する場合は、型変換コードが必要です。

前の例では、教師と生徒のリストをコントローラーからビューに渡すためにViewDataを作成する必要があります。

コントローラコード

public ActionResult IndexViewData()
{
    ViewBag.Message = "Welcome to my demo!";
    ViewData["Teachers"] = GetTeachers();
    ViewData["Students"] = GetStudents();
    return View();
}

コードを見る

@using MultipleModelInOneView;
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
 <p><b>Teacher List</b></p>
@{

   IEnumerable<Teacher> teachers = ViewData["Teachers"] as IEnumerable<Teacher>;
   IEnumerable<Student> students = ViewData["Students"] as IEnumerable<Student>;
}
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in teachers)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>
 <p><b>Student List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in students)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

4.ViewBagの使用

ViewBagはViewDataに似ており、コントローラーからビューにデータを転送するためにも使用されます。ViewBagは動的プロパティです。ViewBagは、ViewDataの単なるラッパーです。

コントローラコード 

public ActionResult IndexViewBag()
{
    ViewBag.Message = "Welcome to my demo!";
    ViewBag.Teachers = GetTeachers();
    ViewBag.Students = GetStudents();
    return View();
}

コードを見る

@using MultipleModelInOneView;
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>

<p><b>Teacher List</b></p>

<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in ViewBag.Teachers)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>

<p><b>Student List</b></p>

<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in ViewBag.Students)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

5.タプルの使用

タプルオブジェクトは、不変で固定サイズの順序付けられたシーケンスオブジェクトです。これは、特定の数と要素のシーケンスを持つデータ構造です。.NET Frameworkは、最大7つの要素のタプルをサポートします。

このタプルオブジェクトを使用して、コントローラーからビューに複数のモデルを渡すことができます。

コントローラコード

public ActionResult IndexTuple()
{
    ViewBag.Message = "Welcome to my demo!";
    var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());
    return View(tupleModel);
}

コードを見る

@using MultipleModelInOneView;
@model Tuple <List<Teacher>, List <Student>>
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p><b>Teacher List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model.Item1)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>
<p><b>Student List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model.Item2)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

6.レンダリングアクションメソッドの使用

部分ビューは、ビュー内の部分ビューを定義またはレンダリングします。Html.RenderActionメソッドを使用してコントローラーアクションメソッドを呼び出すことにより、ビューの一部をレンダリングできます。RenderActionメソッドは、部分ビューでデータを表示する場合に非常に便利です。この方法の欠点は、コントローラーの呼び出しが複数しかないことです。

次の例では、ビュー(partialView.cshtmlという名前)を作成し、このビュー内でhtml.RenderActionメソッドを呼び出して、教師と生徒のリストをレンダリングしました。

コントローラコード  

public ActionResult PartialView()
{
    ViewBag.Message = "Welcome to my demo!";
    return View();
}

/// <summary>
/// Render Teacher List
/// </summary>
/// <returns></returns>
public PartialViewResult RenderTeacher()
{
    return PartialView(GetTeachers());
}

/// <summary>
/// Render Student List
/// </summary>
/// <returns></returns>
public PartialViewResult RenderStudent()
{
    return PartialView(GetStudents());
}

コードを見る

@{
   ViewBag.Title = "PartialView";
<h2>@ViewBag.Message</h2>
<div>
    @{
        Html.RenderAction("RenderTeacher");
        Html.RenderAction("RenderStudent");
    }
</div>

RenderTeacher.cshtml

@using MultipleModelInOneView;
@model IEnumerable<MultipleModelInOneView.Teacher>
 <p><b>Teacher List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>

RenderStudent.cshtml

@using MultipleModelInOneView;
@model IEnumerable<MultipleModelInOneView.Student>

<p><b>Student List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

結論

この記事は、コントローラーからビューに複数のモデルを渡す方法を学ぶのに役立ちます。これが初心者の役に立つことを願っています。

リンク: https://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/

#aspdotnet 

What is GEEK

Buddha Community

ASP.NET MVCで ビュー内の複数のモデル
Einar  Hintz

Einar Hintz

1602560783

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
{
    [Key]
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    [MaxLength(11)]
    public string SWIFTCode { get; set; }

    [DisplayName("Amount")]
    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
}

C#Copy

Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

Hire ASP.Net Developers

Looking to outsource your asp dot net development requirement?

ASP.Net is a special feature of the DOT Net framework created by Microsoft. At HourlyDeveloper.io, we have a team of experienced ASP.Net developers who are experts in delivering custom solutions based on your business requirements. Hire ASP.Net Developers who will provide tailored solutions to facilitate your business growth.

Consult with experts: https://bit.ly/3fNpVqr

#hire asp.net developers #asp.net development company #asp.net development services #asp.net development #asp.net developer #asp.net

Einar  Hintz

Einar Hintz

1602564619

MVC User Registration & Login with ASP.NET Core Identity

User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to MVC application.
  • Customize ASP.NET Core Identity.
  • Identity.UI Design Customization.
  • Next step.

Background

ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.

ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to create an MVC application with ASP.NET Core Identity API

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.

Create an ASP.NET Core Web application

Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Select Model View Controller templet under .NET Core

#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core

ASP.Net Web development Company USA | WebClues Infotech

A versatile Web & Mobile App Development framework technology that is fast, reliable, and easy to use is ASP.NET. ASP.NET gives the developer complete control over development and can be used on any project big or small.

Want to develop a website or mobile app with ASP.NET?

WebClues Infotech with years of experience and a highly skilled development team can be your go-to agency for your Web & Mobile App Development requirements. With an expert developer team of more than 150+ members, WebClues Infotech has successfully delivered more than 1500 projects worldwide.

Want to know more about the ASP.NET framework?

Visit: https://www.webcluesinfotech.com/asp-net-web-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#asp.net web development company #asp.net web development company usa #asp.net development company in india #asp.net development company #.net software development company #hire asp.net developer

Hire Dedicated ASP.NET Developers | ASP.NET Web Development Company

A universally accepted and the most popular framework that can be used for a small or big websites or Web application development projects is the ASP.NET. This framework is majorly used to produce an interactive and data driven web applications.

Are you looking to use an ASP.NET framework for your development needs?

WebClues Infotech offers a dedicated ASP.NET developers where a business can hire a dedicated ASP.NET developer that matches their project requirement. WebClues Infotech also has a flexible pricing structure that suits most project or business requirements.

Want to hire a dedicated ASP.NET developers?

Share your requirements here https://www.webcluesinfotech.com/contact-us/

Book Free Interview with ASP.NET developer: https://bit.ly/3dDShFg

#hire dedicated asp.net developers #hire asp.net developers #hire .net developers #full-stack .net developers india #dedicated .net programmers india #hire asp.net developers or programmers