无法通过$ .ajax将结构参数传递给使用ASP.NET(带有MVC2)的控制器 [英] Cannot pass struct parameters via $.ajax to a controller using ASP.NET (with MVC2)
问题描述
我有一个像这样的模型类:
I have a model class like this:
namespace Models
{
public struct Localization
{
public int Id;
public string LanguageName;
public string LanguageCode;
public DateTime LastUpdate;
}
public class LocalizationModel
{
private List<Localization> _localization;
public LocalizationModel() {
Browse();
}
//create simple list
public void Browse() {
Localization lang = new Localization();
_localization = new List<Localization>();
for ( int i = 1; i <= 3; i++ ) {
lang.Id = i;
lang.LanguageName = "Language name " + i;
lang.LanguageCode = "Language code " + i;
lang.LastUpdate = DateTime.Now;
_localization.Add( lang );
}
}
public bool AddNewLanguage( Localization item ) {
if ( ( item as object ) == null ) {
throw new ArgumentException( "The localization cannot be empty" );
}
_localization.Add( item );
return true;
}
public List<Localization> LocalizationList {
get {
return _localization;
}
}
}
}
以及Home Controller中定义的 Add 方法:
And the Add method defined in Home Controller:
[HttpPost]
public ActionResult Add( Localization sendInfo ) {
bool success = _localization.AddNewLanguage( sendInfo );
return this.Json( new {
msg = success
} );
}
我从jquery ajax函数中调用了该方法,如下所示:
I called that method from jquery ajax function like this:
function sendDataForAdd() {
var sendInfo = { Id: 0,
LanguageName: $("#lang-name").val(),
LanguageCode: $("#lang-code").val(),
LastUpdate: $("#lang-update").val()
};
$.post('/Home/Add', sendInfo, doneLanguageAdded, 'json');
function doneLanguageAdded(msg) {
if (msg) {
alert("The language was added successfully !");
window.location.refresh(true);
}
else {
alert("The language was not added in list !");
}
}
}
问题是控制器的Add
功能参数-> sendInfo
变为空.
javascript变量会正确使用输入值.
问题是来自Model的struct
还是什么?
The problem is that the Add
function parameter -> sendInfo
from controller becomes null.
The javascript variables take correctly the input values.
The problem is the struct
from Model or what ?
我尝试了其他情况.我定义了一个具有所有属性的类,并在LocalizationModel
类中使用它.它与jquery ajax完美配合,并将正确的参数传递给控制器功能.
I tried other scenario. I defined a class with all properties and use it in LocalizationModel
class. It works perfectly with jquery ajax and pass correct parameter to controller function.
为什么使用struct
时,控制器参数为null?有一个把戏吗?
Why if I use struct
, the controller parameter is null ? There are a trick ?
我使用Visual Studio在控制器功能上设置了一个断点,并检查了参数.
I put a breakpoint to controller function (using Visual Studio) and I checked the parameter.
Id和其他变量为null.我附了一张照片:
Id and other variables are null. I attached a picture:
谢谢
推荐答案
您的结构需要具有getter和setter.
Your struct needs to have getters and setters.
public struct Localization
{
public int Id {get; set;}
public string {get; set;}
public string {get; set;}
public DateTime {get; set;}
}
这篇关于无法通过$ .ajax将结构参数传递给使用ASP.NET(带有MVC2)的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!