2014-10-29 55 views
0

在我的控制器中有这样的东西。在使用Javascript提交表单时传递对象

public ActionResult GetResult(Employee employee){ 
    return RedirectToAction("Index","Employee"); 
} 

我不能使用Ajax调用,因为它会做一个帖子并等待响应,而不是提交。

当我有这样的事情,它的作品。

[HttpPost] 
public ActionResult GetResult(string firstName,string lastName){ 
    return RedirectToAction("Index","Employee"); 
} 


In javascript 


    var form = $("#Employee); 
    form.attr('action','Employee/Index?firstName='Tim'&lastName='Tom'); 
    form.submit(); 

上面的作品当传递参数作为querystring.But我不知道如何传递一个对象,而做post。我尝试使用$ .post。但它没有奏效。

谢谢。

+0

如果'Employee'包含属性'firstName'和'lastName'然后再'公众的ActionResult调用getResult(员工员工)'会的工作,但你为什么没有该属性的控件? – 2014-10-29 03:24:58

+0

如何传递QueryString中的对象?我相信'Employee/Index?employee = objectEmployee'是不可能的。 – Bala 2014-10-29 03:46:34

+0

当然没有(Http对c#类一无所知)。但是'form.attr('action','Employee/Index?firstName ='Tim'&lastName ='Tom');'如果'Employee'包含这两个属性,则工作。你究竟想要做什么? – 2014-10-29 03:49:50

回答

1

jQuery的POST在MVC的工作原理是这样的:

由于您的控制器的操作方法是:

public ActionResult GetResult(Employee employee) 
{ 
    return RedirectToAction("Index","Employee"); 
} 

您可能希望在修改jQuery的POST调用此方法

var postData=function() 
    { 

     //prepare javascript object 
       var employee= 
       { 
        firstName:"firstname", 
        lastName:"lastname" 
       }; 
     $.post('/GetResult',employee,function(data){ 
     //process the data here using the the data present in data obj 
     }); 
    } 

型粘结剂在mvc中检查与你有&模型的JavaScript对象中的相同参数,它也应该匹配动作的参数名称方法到JavaScript对象名称。

让我知道这是否适合你。

感谢