.net mvc接收參數為null的解決方案


1、通過對象接收請求數據時的null

必須為對象的屬性設置get與set

private System.String _EMail = System.String.Empty;
        public System.String EMail
        {
            get {return _EMail;}
            set {_EMail = value;}
        }

  

 

2、通過ajax傳遞的empty在對象中自動轉換為null

第一個解決方案

[DisplayFormat(ConvertEmptyStringToNull = false)]
public string test{get;set;}

 

第二個解決方案

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AiAn.GPS.Web.Models
{
//重寫DataAnnotationsModelMetadataProvider方法中的CreateMetadata方法 public class MyDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var md = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); DataTypeAttribute dataTypeAttribute = attributes.OfType<DataTypeAttribute>().FirstOrDefault(); DisplayFormatAttribute displayFormatAttribute = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault(); if (displayFormatAttribute == null && dataTypeAttribute != null) { displayFormatAttribute = dataTypeAttribute.DisplayFormat; } if (displayFormatAttribute == null) { md.ConvertEmptyStringToNull = false; } return md; } } }

//在Global.asax的Application_Start方法中,重新覆蓋原有對象
ModelMetadataProviders.Current = new AiAn.GPS.Web.Models.MyDataAnnotationsModelMetadataProvider();

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM