您的位置:首页 > 其它

MVC常见问题小总结

2013-05-29 15:41 344 查看
转自:http://www.cnblogs.com/janes/archive/2012/07/10/2583201.html

最近刚开始在项目中使用MVC,(ps:不要笑我老土啊)。使用的过程中遇到了一些小问题,记录下来以便日后翻阅。

在MVC中项目中使用JQuery,$.Post方法提交数据时产生中文乱码现象?
      解决方法:

在$.post时进行数据编码,使用escape方法

$.post("@Url.Action("AddFriendLink" , "Setup")" ,{"Name" :escape(name)},function(data){

if(data>0){

                    alert( '添加成功!' );

                    window.location.reload();

                }

else{

                    alert( '添加失败!' );

                }

            });

在后台进行解码,使用Server.UrlDecode方法。

public JsonResult Add(string Name)

{

     DemoClass demoClass= newDemoClass 

            {

                Name = Server.UrlDecode(Name)

            };

     int result = demoService.Add(demoClass);

     return Json(result);

}

2. MVC中如何设置文本框的宽度?
    其实这个本不算是问题,不过刚开始还是写错了。

刚开始写的是:

@Html.TextBoxFor(model => model.Name, new { width="300px" })             (×)

发现没有效果。

实施了第二方案,搞定了。

@Html.TextBoxFor(model => model.Name, new {@style = "width:300px" })  (√)

3.Html.RadioButtonFor怎么使用呢?
   像下面这样就可以了。当Model.IsStudent=true时会自动选中第一项,以此类推。

@Html.RadioButtonFor(model=>model.IsStudent,true)是

@Html.RadioButtonFor(model => model.IsStudent, false)否

4. @helper自定义方法

@helper GetStatusName(int status)

    {

       //code block

    }

调用时直接使用@GetStatusName(2)即可。

5.model多级引用时,对应的html?

@ Html.TextBoxFor(model => model.Topic.Title)

对应生成的HMTL代码为:

<input name="Topic.Title" class="ConInpon"id="Topic_Title" Onkeyup="getLen(this)" type="text"/>

在写脚本的时候要注意了啊。

6.DropDowlList控件数据绑定的几种常用方式?

①下拉框中的选项为几个简单的固定值。

@Html.DropDownList("ProvinceId", new SelectListItem[]{

                      new SelectListItem{ Text="选择类别",Value="0", Selected=true},

                      new SelectListItem{Text="类别A",Value="1"},

                      new SelectListItem{Text="类别B",Value="2"}

                      })

②将数据封装为SelectList类型,并且放在ViewBag中进行传递。

controller层:

IList< Person> personList =personService.GetList();

ViewBag.personId= new SelectList(personList , "Id", "Name", queryParam.EditorId);

Id 和 Name 分别为 personList 要选择的 对应
SelectList  Text 和 Value

View层:直接根据ID进行绑定就可以了。

@Html.DropDownList( "personId")

带有默认值

@Html.DropDownListFor(model => model.PersonID,
(SelectList)ViewBag.
personId)

③如果页面中的数据比较多,直接都放在viewbag中传递会比较乱,我们可以将页面中需要的数据封装成一个类,其中Select类型被封装为一个属性。

封装类

public class IndexView

{

   public SelectList PersonList{get;set;}

   …

}

controller: 对IndexView中的属性赋初始值。

IList< Person> personList =personService.GetList();

IndexView indexView = new IndexView ()

            {

                     PersonList= new SelectList(personList , "Id", "Name", personList )

            };

            ViewBag.indexView = indexView;

View:

@ Html.DropDownListFor(x=>queryParam.PersonId,indexView.PersonList)

7.异步提交表单时,要记得Ajax.BeginForm哟!
   做表单提交时,绕的小弯子:

刚开始想用@Html.BeginForm()+MVC3验证来实现,可是想异步提示结果啊。
用Jquery中的.post方法提交,那就得把验证加在客户端脚本了。
后来突然想起了老被我遗忘了的Ajax.BeginForm()方法。实现了我的需求。(*^__^*) 嘻嘻……

@ using (Ajax.BeginForm( "Index", "Manage" , new AjaxOptions

{

    HttpMethod = "Post",

    OnSuccess = "Success",

    OnFailure = "Failure"

}))

    {

     @Html.ValidationSummary(true)

     @ Html.TextBoxFor(model => model.Name, new { @style = "width:300px" })

     @Html.ValidationMessageFor(model => model.Name)

    }

////脚本提示执行结果

<script language="javascript" type ="text/javascript">

function Success() {

        alert( "修改成功" );

    }

function Failure() {

        alert( "修改失败!" );

    }

</script>

其中还可以设置  UpdateTargetId属性,执行结果后用来显示执行结果。

重要的一点是要添加

<script src=" @Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js" )" type="text/javascript"></script >

现在基本成功了。

 

8:关于Ajax.BeginForm乱码的疑问

还有最后一个问题是产生了中文乱码现象?用Html.BeginForm没问题,用Ajax.BeginForm就会出现乱码。(博问地址

最后终于找到原因了:
view里面和web.config里的编码有冲突了:

view:使用ajax.BeginForm需要添加该引用

      <script src=" @Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js" )" type="text/javascript"></script >

web.config: 网站编码要求采用gb2312

    <globalization fileEncoding=" gb2312" requestEncoding =" gb2312" responseEncoding=" gb2312" culture =" zh-CN" />

还希望各位大牛能够慷慨的提供一种比较好的解决方案,这里是测试项目。 【附件:中文乱码demo

 

对于这个问题,JohnnyYan给出了详尽的回答,在此深表感谢

 

在MVC 1,2版本中,他们使用自己的Ajax类库来实现ajax请求,相应的js文件为MicrosoftAjax.js,MicrosoftMvcAjax.js

但是程序员更喜欢jQuery,“write less, do more ”

后来微软终于意识到开源的重要性,并且开始接受jQuery,在MVC3开始发布了jQuery.Ajax.Unotrusive JavaScript library(非介入式的javascript)。并且将jQuery作为默认的ajax框架。

在web.config中增加client side validation and unobtrusive javascript 两个配置

<add key="ClientValidationEnabled" value="true" /> 

<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

客户端验证是基于jquery.validate.js和jquery.validate.unobtrusive.js的,当你在一个view中包含了这两个文件时,你在Model中声明的data annotation才会被解析。这时你打开你表单查看页面的源代码,可以看到相应的input fields都具有包含验证规则的HTML5的data-*属性,这些属性将被Microsoft unobtrusive validation script读取并配置jquery validate.

unobtrusive javascript 是基于jQuery的,在使用AjaxHelper时(ActionLink 或者BeginForm),他会自动向你的控件中添加data-属性(HTML5 属性),这些属性之后会被jquery.unobtrusive-ajax.js进行解析,所以要在页面中引入该文件。

例如:

@Ajax.ActionLink("UTC", "GetTime", new { zone = "utc" }, new AjaxOptions { UpdateTargetId = "myResults" })

生成的代码是:

<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#myResults" href="/Home/GetTime?zone=utc">UTC</a>

jquery.unobtrusive-ajax.js作用就是解析data-ajax-mode等属性,然后发出ajax请求的(可以看下这个文件的代码),乱码就是因为你没有引入该文件

如果不想使用jquery,改为false即可

<add key="UnobtrusiveJavaScriptEnabled" value="false" /> 

同时需要在页面中引入MicrosoftAjax.js,MicrosoftMvcAjax.js



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: