私はasp.net mvcでアプリケーションを書いています。ViewModel をパラメーターとして使用するアクション付きのコントローラーがあります。そのmvcコントローラーにjquery postでフォームデータを送信する方法。
73752 次
2 に答える
43
$.post("Yourcontroller/YourAction", { FirstName : $("#txtFirstName").val(), LastName : $("#txtLastName") } ,function(data){
//do whatever with the response
});
渡す ViewModel プロパティ名とパラメータは同じである必要があります。すなわち:ビューモデルには、彼のように呼び出さFirstName
れた2つのプロパティが必要ですLastName
public class PersonViewModel
{
public string FirstName { set;get;}
public string LastName { set;get;}
// other properties
}
そして、Post アクション メソッドは型のパラメータを受け入れる必要がありますPersonViewModel
[HttpPost]
public ActionResult YourAction(PersonViewModel model)
{
//Now check model.FirstName
}
または、ビューが PersonViewModel に厳密に型指定されている場合は、jQueryserialize
メソッドを使用してシリアル化されたフォームをアクション メソッドに送信するだけです。
$.post("Yourcontroller/YourAction", $("#formId").serialize() ,function(data){
//do whatever with the response
});
編集:コメントによると
Serialize
Child プロパティも処理します。このようなProfessionというクラスがあるとします
public class Profession
{
public string ProfessionName { set; get; }
}
そして、あなたの PersonViewModel にはタイプのプロパティがありますProfession
public class PersonViewModel
{
//other properties
public Profession Profession { set; get; }
public PersonViewModel()
{
if (Profession == null)
Profession = new Profession();
}
}
ビューからデータを入力すると、HttpPost アクション メソッドでこれらのデータを取得できます。
于 2012-05-29T16:55:35.790 に答える
9
var myData = {
Parameter1: $("#someElementId").val(),
Parameter2: $("#anotherElementId").val(),
ListParameter: { /* Define IEnumerable collections as json array as well */}
// more params here
}
$.ajax({
url: 'someUrl',
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(myData)
});
[HttpPost]
public JsonResult Create(CustomViewModel vm)
{
// You can access your ViewModel like a non-ajax call here.
var passedValue = vm.Parameter1;
}
フォーム全体をシリアル化し、コントローラーのアクション メソッドに渡すこともできます。あなたのajax呼び出しで:
data: $('form').serialize()
于 2012-05-29T16:47:03.817 に答える