将JSON数据发送到MVC Controller操作MVC 5Application

时间:2014-05-30 10:41:17

标签: javascript jquery asp.net asp.net-mvc asp.net-mvc-5

我知道这已经被回答了很多次,我花了四天时间阅读并尝试了大部分解决方案,但无济于事。

我有一个JS函数,它从webform读取输入,并将其发送到控制器。我有js功能:

 function Savedata() {
    var inputData = $("div.dataCreate").find(":input");
           jQuery.ajax({
        type: "POST",
        url: "@Url.Action("Savedata", "dtype")",
        data: inputData.serialize()
    }).done(function (result) {
        $("#divdata").html(result);
    });

}

我有我的行动:

[HttpPost]

    public ActionResult Savedata(data dataData)
    {
        if (ModelState.IsValid)
        {
            _data.Createdata(dataData);
        }
        var model = new dtype();
        var dtypes=_dtypeServices.Getdtypes();
        model.dtypes= new dtypes(){dtypeTypes = dtypes};
        return PartialView("Index", model);
    }

这是我的模特:

[Serializable]
public class data : dtypeType
{
    public int dataID { get; set; }
    public int reftypeID { get; set; }
    [DisplayName("data Name:")]
    public string dataName { get; set; }
    [DisplayName("data Description: ")]
    public string dataDescription { get; set; }
    public DateTime EndDate { get; set; }
    public DateTime DateCreated { get; set; }
    public reftype reftype { get; set; }
    [DisplayName("data Code: ")]
    public string dataCode { get; set; }

    //public dataOperation dataOp { get; set; }


    public override string Name
    {
        get { return "data"; }
    }

    public override string Description
    {
        get { return "data Description"; }
    }

    public override bool HasCustomHeader
    {
        get
        {
            return true;
        }
    }

    public override bool HasContent
    {
        get
        {
            return true;
        }

    }
}
public abstract class dtypeType
{
    public abstract string Name { get; }

    public abstract string Description { get; }

    public int Id { get; set; }
    public virtual string Type { get { return GetType().Name; } }
    public abstract bool HasCustomHeader { get; }
    public abstract bool HasContent { get; }

    internal IEnumerable<ValidationResult> CustomValidations(string idPrefix, ValidationContext validationContext)
    {
        var context = new ValidationContext(this, null, null);
        foreach (var property in GetType().GetProperties())
        {
            var clientSideAttributes =
                property.GetCustomAttributes(typeof(ClientSideValidationAttribute), false) as
                    ClientSideValidationAttribute[];
            context.MemberName = string.Format("{0}.{1}", idPrefix, property.Name);
            var displayNameAttribute =
                property.GetCustomAttributes(typeof(DisplayNameAttribute), false)
                    .Cast<DisplayNameAttribute>()
                    .SingleOrDefault();
            if (displayNameAttribute != null)
                context.DisplayName = displayNameAttribute.DisplayName;
            else
                context.DisplayName = displayNameAttribute.DisplayName;
            foreach (var clientSideAttribute in clientSideAttributes)
            {
                var result = clientSideAttribute.ValidateValue(property.GetValue(this, null), context);
                if (result != null) yield return result;
                {

                }
            }
        }
    }
}

当我检查发送给控制器的内容时​​,我得到了这个:

"dtypes.dtypeTypes[1].reftype.reftypeName=3&dtypes.dtypeTypes[1].dataName=dfds&dtypes.dtypeTypes[1].dataDescription=dsgsdgh&dtypes.dtypeTypes[1].dataCode=33"

我有一个模型活页夹:

public class dtypeTypeBinders : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var type = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Types").AttemptedValue;
        try
        {
            var baseType = typeof(dtypeType);
            var targetType =
                Type.GetType(string.Format("{0}.{1},{2}", baseType.Namespace, type, baseType.Assembly.GetName().Name));

            var typeBindingContext = new ModelBindingContext(bindingContext)
            {
                ModelName = bindingContext.ModelName,
                ModelMetadata = new ModelMetadata(ModelMetadataProviders.Current, null, null, targetType, null)
            };
            return base.BindModel(controllerContext, typeBindingContext);
        }
        catch (Exception e)
        {
            throw new Exception(string.Format("unknown dtype type'{0}'", type), e);

        }
    }


}

但是在行动中我得到了空值,我想知道我错过了什么以及我做错了什么。

1 个答案:

答案 0 :(得分:0)

在ajax调用中添加一个与MVC操作方法参数名称dataData匹配的参数名称

data: {dataData: JSON.stringify(inputData.serializeArray())}

您也可以使用Requst.Params["dataData"]在操作方法中对其进行验证,并确保在Request对象中获取数据。