从Controller获取返回值到javascript

时间:2015-11-25 11:33:04

标签: javascript c# asp.net .net

我想要的是,我想检查数据库中是否有文件。为此,我在控制器中有一个方法,它检查这个并返回相应大小写的布尔值。它看起来像这样:

  jQuery(".form-js-pop-vedam").submit(function () {
		var thisform = jQuery(this);
		jQuery('.required-error',thisform).remove();
		
		var pmail	= jQuery("#pmail").val();
		var pphone	= jQuery("#pphone").val();
		var psubject	= jQuery("#psubject").val();
		
		var data = {'pmail':pmail,'pphone':pphone,'psubject':psubject}
		
		 if (pmail == "") {
			 jQuery("#pmail").after('<span class="form-description  required-error">Required field.</span>');
		}else {
			jQuery("#pmail").parent().find('.required-error').remove();
		}
		if (pphone == "") {
			jQuery("#pphone").after('<span class="form-description   required-error">Required field.</span>');
		}else {
			jQuery("#pphone").parent().find('.required-error').remove();
		}
		
		if ( pmail != "" && pphone != "" ) {
			jQuery.post("contact_us_pop-vedam.php",data,function (result) {
				if (result == "done") {
					
    thisform.prepend("<div class='alert-message success-amairo'><i      class='icon-ok'></i><p><span>Vedam brochure was sent to your mail. Thank    you!</span></p></div>");
					jQuery("#pmail").val("");
					jQuery("#pphone").val("");
					
				}
			});
		 }
		return false;
	 });
	

我只是检查是否有任何文件分配给给定的员工。

现在我想在视图中从我的javascript调用此方法,并获取返回值,以便我可以让用户知道,是否有分配给所选员工的文件。它可能看起来像这样:

 
    <form class="form-style form-js-pop-vedam" action="contact_us_pop-vedam.php" method=post>
  <input type="hidden" name="psubject" id="psubject" value="Brochure   Download from Vedam Page">

  <div class="col-md-6" ><input type=email class=required-item id=pmail name=pmail value="" aria-required=true placeholder="Your Email*"></div>
  <div class="col-md-6 " ><input class=required-item aria-required=true id=pphone name=pphone value="" placeholder="Your Phone*"></div>
  <div class="col-md-6 " ><input name=submit type=submit value="Download Now >" class="submit_buttom buttonColor-side" id="Brochure_Download"></div>
  </form>

 

所以现在我的问题是,如何从控制器中的方法获取返回值?

4 个答案:

答案 0 :(得分:2)

我建议在这里做些改动:

将您的controller方法更改为return类型ActionResultJsonResult,我更愿意JsonResult就够了,并且重新Json回复来自controller,并使用 $.get 操作此方法。您还需要将参数更改为string,因为parameter将作为Json string收到。

public JsonResult fileInDb(string eId) //change signature to string and then convert to int 
{
    int empId=Convert.ToInt32(eId);
    using (SLADbContext db = new SLADbContext())
    {
         bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
         if (file)
         {
             return Json(new { result = true },JsonRequestBehavior.AllowGet);
         }
         else
         {
             return Json(new { result = false},JsonRequestBehavior.AllowGet);
         }
    }
}  

现在,您的ajax-get电话会议如下:

$("#get-file").click(function() {
   var eId= $("#EmployeeSelect").val();
   $.get('/YourControllerName/fileInDb',{'eId':eId},function(response){
       //you just need to get the response so $.get is enough to manipulate
       //this will be called once you get the response from controller, typically a callback
       if(response.result) //same result variable we are returning from controller.
       {
            // Let the user download the file he/she requested
            var url = "@Url.Action("GetUploadedFile", "Competence")";
            this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
       } else {
            alert("There is no file assigned to this employee.");
       }
   })
});  

答案 1 :(得分:0)

您需要使用ASP fileInDb功能设置单页脚本,然后使用浏览器中的AJAX与该页面进行通信。如果您不熟悉AJAX,我建议您使用jQuery implementation来帮助您入门。

答案 2 :(得分:0)

在后端创建一个方法来调用,返回一个JsonResult

    public JsonResult fileInDb(int empId)
    {
         // your code - set fileExists to true/false

        JsonResult returnObj = new JsonResult
        {
            Data = new
            {
                FileExists = fileExists ;
            }
        };

        return Json(returnObj);
    }
你的javascript代码中的

使用$ .ajax

       $.ajax({
            cache: false,
            url: '@Url.Action("fileInDb")',
            data: { 'empId': someVar },
            type: 'POST',
            success: function (response) {
                  if (response.Data.FileExists === true) {
                    // do something
                  }   else {
                   // it was false
                  }
                },
            error: function (er) {
                alert('Error!' + er);
            }
        });

答案 3 :(得分:0)

您可以使用jquery和ajax来实现此目的。使用客户端代码中的ajax调用来调用您的方法。以下是一个示例作为参考:Calling controller method from view