search
HomeDatabaseMysql Tutorialmvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

1:添加控制器类文件HomeController.cs其代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcTestData.Models; namespace MvcTestData.Controllers{ public class HomeContr

1:添加控制器类文件HomeController.cs其代码如下:

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

<span>using</span><span> System;
</span><span>using</span><span> System.Collections.Generic;
</span><span>using</span><span> System.Linq;
</span><span>using</span><span> System.Web;
</span><span>using</span><span> System.Web.Mvc;
</span><span>using</span><span> MvcTestData.Models;
</span><span>namespace</span><span> MvcTestData.Controllers
{
    </span><span>public</span> <span>class</span><span> HomeController : Controller
    {
        </span><span>//</span>
        <span>//</span><span> GET: /Home/</span>

        <span>public</span><span> ActionResult Index()
        {
            TestDataContext txtData </span>= <span>new</span><span> TestDataContext();
            </span><span>var</span> result=<span>from</span> info <span>in</span><span> txtData.StuTable
                       </span><span>select</span><span> info;
            ViewData[</span><span>"</span><span>data</span><span>"</span>] =<span> result;
            </span><span>return</span><span> View(result);
        }

        </span><span>public</span><span> ActionResult Add(FormCollection form)
        {
            </span><span>string</span> id =form[<span>"</span><span>StuId</span><span>"</span><span>];
            </span><span>string</span> name=form[<span>"</span><span>StuName</span><span>"</span><span>];
            </span><span>string</span> sex = form[<span>"</span><span>StuSex</span><span>"</span><span>];
            </span><span>int</span> age = <span>int</span>.Parse(form[<span>"</span><span>StuAge</span><span>"</span><span>]);
            </span><span>string</span> address = form[<span>"</span><span>StuAddress</span><span>"</span><span>];

            StuTable stu </span>= <span>new</span><span> StuTable();
            stu.StuId </span>=<span> id;
            stu.StuName </span>=<span> name;
            stu.StuSex </span>=<span> sex;
            stu.StuAge </span>=<span> age;
            stu.StuAddress </span>=<span> address;

            </span><span>try</span><span>
            {
                </span><span>using</span> (<span>var</span> db = <span>new</span><span> TestDataContext())
                {
                    db.StuTable.InsertOnSubmit(stu);
                    db.SubmitChanges();
                    ViewData[</span><span>"</span><span>result</span><span>"</span>] = <span>"</span><span>ok</span><span>"</span><span>;
                }
            }
            </span><span>catch</span><span> 
            {
                ViewData[</span><span>"</span><span>result</span><span>"</span>] = <span>"</span><span>fail</span><span>"</span><span>;
                </span><span>throw</span><span>;
            }
            </span><span>return</span> View(<span>"</span><span>Add</span><span>"</span><span>);
        }

        </span><span>public</span><span> ViewResult AddInfo()
        {
            </span><span>return</span> View(<span>"</span><span>AddInfo</span><span>"</span><span>);
        }

        </span><span>public</span><span> ViewResult Delete()
        {
            </span><span>int</span> id = Int16.Parse(Request.Form[<span>"</span><span>id</span><span>"</span><span>]);
            </span><span>try</span><span>
            {
                </span><span>using</span> (<span>var</span> db = <span>new</span><span> TestDataContext())
                {
                    db.StuTable.DeleteOnSubmit(db.StuTable.First(info </span>=> info.ID ==<span> id));
                    db.SubmitChanges();
                    ViewData[</span><span>"</span><span>result</span><span>"</span>] = <span>"</span><span>ok</span><span>"</span><span>;
                }
            }
            </span><span>catch</span><span>
            {
                ViewData[</span><span>"</span><span>result</span><span>"</span>] = <span>"</span><span>fail</span><span>"</span><span>;
                </span><span>throw</span><span>;
            }
            </span><span>return</span> View(<span>"</span><span>Delete</span><span>"</span><span>);
        }

       

    }
}</span>
View Code

 

2:为models文件夹添加linq to sql 类文件然后把数据库中的表copy 进来

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)
3:为控制器中的Action添加各自的视图

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

4 视图Index.cshtml的代码

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

<span>@using MvcTestData.Models
</span>


    <title>Index</title>


    <div>
    <table border="<span">"<span>0</span><span>"</span> cellspacing=<span>"</span><span>0</span><span>"</span> cellpadding=<span>"</span><span>0</span><span>"</span> width=<span>"</span><span>100%</span><span>"</span> style=<span>"</span><span>text-align:center</span><span>"</span> >
        <tr>
            <th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>住址</th>
<th>操作</th>
        </tr>
<span>
@foreach (StuTable info </span><span>in</span> (ViewData[<span>"</span><span>data</span><span>"</span>] <span>as</span> IEnumerable<stutable><span>))
{
   </span><tr>
        <td>@info.ID</td>
        <td>@info.StuId </td>
        <td>@info.StuName </td>
        <td>@info.StuSex </td>
        <td>@info.StuAge </td>
        <td>@info.StuAddress </td>
        <td>
            <form action="<span">"<span>/Home/Delete</span><span>"</span> method=<span>"</span><span>post</span><span>"</span>>
                <input type="<span">"<span>hidden</span><span>"</span> name=<span>"</span><span>id</span><span>"</span> value=<span>"</span><span>@info.ID</span><span>"</span>/>
                <input type="<span">"<span>submit</span><span>"</span> value=<span>"</span><span>删除</span><span>"</span>/>
              
            </form>
             
        </td>
   </tr>
<span>
}
          </span></stutable>
</table>
        <br><span>
        @Html.ActionLink(</span><span>"</span><span>添加个人信息</span><span>"</span>,<span>"</span><span>AddInfo</span><span>"</span>,<span>"</span><span>Home</span><span>"</span><span>)
    </span>
</div>

View Code

5 视图 Add.cshtml的代码

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

<span>@model MvcTestData.Models.StuTable

@{
    ViewBag.Title </span>= <span>"</span><span>Add</span><span>"</span><span>;
}
@if(ViewData[</span><span>"</span><span>result</span><span>"</span>].Equals(<span>"</span><span>ok</span><span>"</span><span>))
{
    </span><p>添加成功</p><span>
}
</span><span>else</span><span>
{
    </span><p>添加失败</p><span>
}</span>
View Code

6 视图AddInfo.cshtml代码

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

<span>@model MvcTestData.Models.StuTable

@{
    ViewBag.Title </span>= <span>"</span><span>AddInfo</span><span>"</span><span>;
}

</span><h2 id="AddInfo">AddInfo</h2>
<span>
@using(Html.BeginForm(</span><span>"</span><span>Add</span><span>"</span>,<span>"</span><span>Home</span><span>"</span><span>,FormMethod.Post))
{
    </span><p>Student 学号:@Html.TextBoxFor(x=>x.StuId)</p>
    <p>Student 姓名:@Html.TextBoxFor(x=>x.StuName)</p>
    <p>Student 性别:@Html.TextBoxFor(x=>x.StuSex)</p>
    <p>Student 年龄:@Html.TextBoxFor(x=>x.StuAge)</p>
    <p>Student 住址:@Html.TextBoxFor(x=>x.StuAddress)</p>
    <input type="<span">"<span>submit</span><span>"</span> value=<span>"</span><span>Add</span><span>"</span> /><span>
}

 </span>
View Code

7 视图Delete.cshtml代码

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

<span>@model MvcTestData.Models.StuTable

@{
    ViewBag.Title </span>= <span>"</span><span>Delete</span><span>"</span><span>;
}

@if (ViewData[</span><span>"</span><span>result</span><span>"</span>].Equals(<span>"</span><span>ok</span><span>"</span><span>))
{
    </span><p>删除成功</p><span>
}
</span><span>else</span><span>
{
   </span><p>删除失败</p><span>
}</span>
View Code

8 最终测试结果图:

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQL String Data Types: A Comprehensive GuideMySQL String Data Types: A Comprehensive GuideMay 08, 2025 am 12:14 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

Mastering MySQL BLOBs: A Step-by-Step TutorialMastering MySQL BLOBs: A Step-by-Step TutorialMay 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BLOB Data Type in MySQL: A Detailed Overview for DevelopersBLOB Data Type in MySQL: A Detailed Overview for DevelopersMay 07, 2025 pm 05:41 PM

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

How to Add Users to MySQL from the Command LineHow to Add Users to MySQL from the Command LineMay 07, 2025 pm 05:01 PM

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

What Are the Different String Data Types in MySQL? A Detailed OverviewWhat Are the Different String Data Types in MySQL? A Detailed OverviewMay 07, 2025 pm 03:33 PM

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools