프로그래밍

첨부파일업로드를 Ajax로

Jinwookoh 2014. 8. 18. 23:24

jquery.form을 이용하면 

1. ajax를 할때 첨부파일 업로드가 가능하다.

2. valid 체크 후 포커스가 가능하다.


[다운로드]

http://malsup.com/jquery/form/


[사용예]

1. 다음 jquery.form.min.js 추가하기

 

2. 컨트롤러 액션 끝에

           bool isSuccess = false;
            string elementID = string.Empty;
            string message = "저장하지 못했습니다.";
            string redirectURl = string.Empty;
            if (ModelState.IsValid)
            {
                try
                {
                    var result = 1;
                    if (result > 0)
                    {
                        isSuccess = true;
                        message = "저장하였습니다.";
                        redirectURl = "주소...";
                    }
                }
                catch (M2CASTException ex)
                {
                    this.WriteErrorLog(ex);
                    // 오류
                    message = ex.Message;
                }
                catch (Exception ex)
                {
                    this.WriteErrorLog(ex);
                }
            }
            else
            {
                var ModelError = from n in ModelState.Where(x => x.Value.Errors.Count > 0)
                                 select new { n.Key, n.Value };
                if (ModelError.Any())
                {
                    elementID = ModelError.First().Key;
                    message = ModelError.First().Value.Errors.First().ErrorMessage;
                }
            }
            return Json(new { Success = isSuccess, ElementID = elementID, Message = message, RedirectURL = redirectURl }, "text/html");

- ASP.NET MVC 에서 valid체크를 했을 때 실패한 ElementID와 메시지를 추출

 

3. 스크립트로 호출

$("#empForm").ajaxSubmit({
                type: "POST",
                dataType: 'text',
                url: $("#empForm").attr("action"),
                data: $("#empForm").serialize(),
                success: function (data) {
                    data = $.parseJSON(data);
                    Common.AjaxSuccess(data);
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });

 

4. 공통스크립트

this.AjaxSuccess = function fn_AjaxSuccess(result) {
        if (result.Success == "true" || result.Success == true) {
            alert(result.Message);
            //페이지 이동
            
            if (result.RedirectURL != undefined) {
                window.location.href = result.RedirectURL;
            }
        } else {
            alert(result.Message);
            //해당 Element focus
            if (result.ElementID != undefined) {
                $("input[name='" + result.ElementID + "']").focus();
            }
        }
    }

'프로그래밍' 카테고리의 다른 글

XSL 정렬방법  (0) 2015.02.13
C# Html을 text로 바꾸기  (0) 2014.08.18
asp.net mvc View를 html로 뽑기  (0) 2014.08.18
Entity에서 합계 구할때 주의  (0) 2014.08.18
crossdomain.xml  (0) 2014.08.18