mvc基础系列说谈(5)——参数与值传递,提交数据

准备工作:

现在添加Customer控制器,同时,在创建控制器的时候,添加CreateDeleteDetail动作。

Customer的模型结构为:

Customer类:CustomerIDLastNameFirstName

现在控制器情况为: 

代码
public class CustomerController : Controller
{
        
public ActionResult Index()
        {
            
return View();
        }

        
public ActionResult Details(int id)
        {
            
return View();
        }

        
public ActionResult Create()
        {
            
return View();
        } 

        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult Create(FormCollection collection)
        {
            
try
            {
                 
return RedirectToAction("Index");
            }
            
catch
            {
                
return View();
            }
        }

        
public ActionResult Edit(int id)
        {
            
return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult Edit(int id, FormCollection collection)
        {
            
try
            {
                
return RedirectToAction("Index");
            }
            
catch
            {
                
return View();
            }
        }
}

可以看到,除IndexDetails动作外,其它的CU全是两个动作,由于修饰标签的作用而在不同情况下调用动作来返回视图。

(一)添加列表

Views中添加Customer文件夹,然后在此文件夹中添加Index视图。并指定强类型Customer,并指定自动生成视图内容:List

代码就不贴了。然后在动作中为视图指定model

public ActionResult Index()
{
    IList
<Customer> _list = dd.ShowList();
    
return View(_list);
}

Index

CustomerId

FirstName

LastName

 

3

Tom

 

编辑 | 详细

2

Tom

Song

编辑 | 详细

Create New

 

现在点击第一条的详细,会发生什么事:

<%= Html.ActionLink("详细""Details"new { /* id=item.PrimaryKey */ })%>

通过ActionLink来重定向到控制器下的Details动作。

public ActionResult Details(int id)
{
  
return View();
}

这个动作接受一个参数,但在列表中没有提供参数:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'Web.Controllers.CustomerController'. To make a parameter optional its type should be either a reference type or a Nullable type.

参数名: parameters

因为在Details方法(动作)动作中要求有一个int型参数,但在传递时传递的是一个Null值,解决:

1 Details方法的参数改为可空整形

2 传递参数

现在为Details动作添加视图,Details。这个就不说了。然后再点详细:

会提示:未将对象引用设置到对象的实例。这是因为还没有为详细视图返回model实例。现在在Details方法(动作)中,添加:

public ActionResult Details(int? id)
{
   Customer customer 
= new Customer();

   
if (id.HasValue)
       customer 
= dd.GetCustomer((int)id);

   
return View(customer);
}

现在再点详细看看,会发现,可以预览,但没有值,这个很容易理解,传递的值为Null,所以int? id就为空,所以返回的是一个空实例(只有实例的默认值)。这时候可以为其指定一个路由默认值:

new { controller = "News", action = "NewsList", id = "2" },它取的的是id=2这个默认值

 

接下来为详细传递id参数,即在列表视图中为详细链接添加参数:

<%= Html.ActionLink("详细", "Details", new { id=item.CustomerId })%>

其中id部分与Details动作的参数名相同。现在的详细就可以正常了。

Index

CustomerId

FirstName

LastName

 

3

Tom

 

编辑 | 详细

2

Tom

Song

编辑 | 详细

 

 

Details

CustomerId: 3

FirstName: Tom

 

 

(二)创建Create视图

在创建过程中,选择强类型,并选择Customer实体。

然后Create视图的代码就不贴了。简单的说明一下:

·验证控件,每个创建的输入文本框都有相应的ValidationMessage

·Form,添加了表单,但没有指定动作类型,所以这里默认的是Post

    Post:表单在提交时,填写在表单中的数据将在底层发送到action=“url”中的url

    Get:表单在提交时,填写在表单中的数据会和action=“url”中的url编码在一起

·输入框,这个会依赖此页的强类型Model而对应生成。

Inherits="System.Web.Mvc.ViewPage<Web.Models.Customer>"

然后看控制器中,可以看到有两个动作:

public ActionResult Create()
{
    
return View();


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
    
try
    {
       
return RedirectToAction("Index");
    }
    
catch
    {
       
return View();
    }
}

第一个没有参数,返回空视图,它就是为导航到Create页。且默认Methodget

第二个用于处理创建工作,它的Method被标签修饰为Post,它只接受post动作。

还以列表页Index为例,当点击

<%= Html.ActionLink("Create New", "Create") %>时,会getCreate动作。这时执行第一个动作,返回空视图(其实这个视图与返回一个没有值的model一样)

然后在创建时,提交表单,会提交到Create动作,这个时候接爱的谓词为Post[AcceptVerbs(HttpVerbs.Post)]

所以,在这个动作中做数据添加操作。

(1)参数为FormCollection collection

这个表单集合包含了post过来的表单元素。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
    
try
    {
       Customer customer 
= new Customer 
       { 
           FirstName 
= collection["FirstName"],
           LastName
=collection["LastName"
       };
       dd.Add(customer);
       
return RedirectToAction("Index");
    }
    
catch
    {
       
return View();
    }
}

 

(2)参数为持久实体

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Customer customer)
{
    
try
    {
        dd.Add(customer);
        
return RedirectToAction("Index");
    }
    
catch
    {
        
return View();
    }
}

这个比较方便。

3)通过Form方法得到参数。

string strFirstName = Request.Form["FirstName"].ToString();
string strLastName = Request.Form["LastName"].ToString();

这个与FormCollection 相同 

Index

CustomerId

FirstName

LastName

 

2

Tom

Song

编辑 | 详细

3

Tom

 

编辑 | 详细

4

编辑 | 详细

5

编辑 | 详细

6

编辑 | 详细

Create New

 

 

(三)删除与编辑与上面的同理

例如:删除可以get方式传递一个id

(四)文件上传

如果有文件上传时,要把Form

enctype="multipart/form-data"

属性设置一下。

HTML enctype 属性

enctype 属性 -- 代表HTML表单数据的编码方式

application/x-www-form-urlencoded:窗体数据被编码为名称/值对.这是标准的编码格式.

multipart/form-data:窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分.

text/plain:窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符.

Form的这个属性的默认值是:application/x-www-form-urlencoded

http头中可以看到:Content-Type:application/x-www-form-urlencoded

 

<input type="file" name="upfile1" />

注意:上传控件的name属性一定要设置,否则提交附件无效!

(1)以默认方式提交文本

FirstName:

LastName:

提交创建:

发送的数据是:

FirstName:松

LastName:武

(2)以默认方式提交上传文件

现在发现,上传文件不能提交到服务器。

查看提交的内容,可以看到:

FirstName=q1&LastName=q2

两个文本属性以kv对传到服务器,而附件:

upfile1=C:\Documents and Settings\Administrator\妗岄潰\Image76.gif

只有一个地址而已

(3) 改用multipart/form-data

这个时候,在http头及提交的数据流里可以看到:

 

Content-Typemultipart/form-data;

boundary=---------------------------7daf1ec01dc

 

-----------------------------7daf1ec01dc

Content-Disposition: form-data; name="FirstName"

 

x

-----------------------------7daf1ec01dc

Content-Disposition: form-data; name="LastName"

X

Content-Disposition: form-data;

name="upfile1"; filename="C:\Documents and Settings\Administrator\妗岄潰\Image76.gif"

Content-Type: image/gif

二进制

 

以上贴出部分内容。

现在,全部的值都可以得到了。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
    
try
    {
       Customer customer 
= new Customer 
       { 
          FirstName 
= collection["FirstName"], 
          LastName 
= collection["LastName"
       };
       dd.Add(customer); 

       
if (Request.Files.Count > 0)
       {
           Request.Files[
0].SaveAs(Server.MapPath("../uploadlist/xx.gif"));
       }

       
return RedirectToAction("Index");
    }
    
catch
    {
       
return View();
    }
}

 

 

原文地址:https://www.cnblogs.com/jams742003/p/1665773.html