0

I have a site that I want to Send few posts for myself.

I'm having a problem posting a photo post. I want to send the photo file that the user uploads to the controller using Jquery Ajax, but this does not happen.

See My HTML Code :

<div class="col-sm-12">
    <div class="card">
        <div class="card-header">
            <strong>ثبت خبر جدید</strong>
        </div>
        <div class="card-block">
            <div class="row">
                <div class="form-group row">
                    <div class="col-md-6">
                        <label for="BlogTitle">سر تیتر خبر</label>
                        <input type="text" class="form-control" id="BlogTitle" placeholder="سر تیتر خبر : مثال تخفیف بر روی تمامی سرویس ها">
                    </div>
                    <div class="col-md-6">
                        <label for="BlogShortDesc">متن کوتاه خبر</label>
                        <input type="text" class="form-control" id="BlogShortDesc" placeholder="به اندازه 110 کاراکتر متن کوتاه وارد کنید">
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label for="BlogLongDesc">متن اصلی خبر</label>
                <textarea class="form-control" id="BlogLongDesc" rows="10" placeholder="متن اصلی خبر خود را وارد کنید"></textarea>
            </div>
            <div class="form-group row">
                <div class="col-md-4">
                    <label for="BlogView">آیا پست نمایش داده شود ؟</label>
                    <label class="switch switch-icon switch-pill switch-success">
                        <input type="checkbox" class="switch-input" id="BlogView" checked>
                        <span class="switch-label" data-on="&#xf00c" data-off="&#xf00d"></span>
                        <span class="switch-handle"></span>
                    </label>
                </div>
                <div class="col-md-4">
                    <label for="BlogFire">آیا خبر مهم است ؟</label>
                    <label class="switch switch-icon switch-pill switch-success">
                        <input type="checkbox" class="switch-input" id="BlogFire">
                        <span class="switch-label" data-on="&#xf00c" data-off="&#xf00d"></span>
                        <span class="switch-handle"></span>
                    </label>
                </div>
                <div class="col-md-4">
                    <label for="BlogCommentEnable">آیا برای این خبر کامنت باز باشد ؟</label>
                    <label class="switch switch-icon switch-pill switch-success">
                        <input type="checkbox" class="switch-input" id="BlogCommentEnable">
                        <span class="switch-label" data-on="&#xf00c" data-off="&#xf00d"></span>
                        <span class="switch-handle"></span>
                    </label>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-sm-4">
                    <label for="BlogDatePublish">تاریخ ارسال خبر</label>
                    @*<div>
                            <label id="BlogDatePublish"><small class="text-success">برای انتخاب تاریخ بر روی من کلیک کنید</small></label>
                        </div>*@
                    <input type="text" class="form-control" id="BlogDatePublish" placeholder="*** تاریخی که کاربر خواهد دید ***">
                </div>
                <div class="form-group col-sm-8">
                    <label for="BlogImage">عکس اصلی خبر</label>
                    <input type="file" class="form-control" id="BlogImage">
                </div>
            </div>

            <div class="row">
                <div class="form-group col-sm-6">
                    <label for="BlogReview">تعداد بازدید پیشفرض خبر</label>
                    <input type="text" class="form-control" id="BlogReview" placeholder="این روش پیشنهاد نمی شود.">
                </div>
                <div class="form-group col-sm-6">
                    <label for="BlogPublisher">ارسال کننده خبر</label>
                    <select class="form-control" id="BlogPublisher">
                        <option>توسط Ajax مقدار دهی می شود.</option>
                    </select>
                </div>
            </div>

            <div class="row">
                <div class="form-group col-sm-4">
                    <label for="PostCategory1">دسته بندی سطح اول خبر</label>
                    <select class="form-control" id="PostCategory1">
                        <option>توسط Ajax مقدار دهی می شود.</option>
                    </select>
                </div>
                <div class="form-group col-sm-4">
                    <label for="PostCategory2">دسته بندی سطح دوم خبر</label>
                    <select class="form-control" id="PostCategory2">
                        <option>توسط Ajax مقدار دهی می شود.</option>
                    </select>
                </div>

                <div class="form-group col-sm-4">
                    <label for="PostCategory3">دسته بندی سطح سوم خبر</label>
                    <select class="form-control" id="PostCategory3">
                        <option>توسط Ajax مقدار دهی می شود.</option>
                    </select>
                </div>
            </div>

            <div class="row">
                <div class="form-group col-md-12">
                    <label for="tags">تگ های خبر را وارد کنید</label>
                    <input type="text" class="form-control" name="tags" id="tags">
                    <label><small class="text-info">نکته : تگ ها را میتوانید با Enter یا Comma از یکدیگر جدا کنید و با BackSpace یا x آنها را پاک کنید.</small></label>
                </div>
            </div>

            @*<div class="row">
                    <div class="form-group col-sm-12">
                        <label for="tagBox">تگ های خبر را وارد کنید</label>
                        <div data-tags-input-name="tag" id="tagBox">
                            Start
                        </div>
                    </div>
                    <label><small class="text-warning">نکته : تگ ها را میتوانید با Enter یا Space از یکدیگر جدا کنید و با BackSpace و Delete آنها را پاک کنید.</small></label>
                </div>*@

        </div>
        <div class="card-footer">
            <a href="@Url.Action("BlogList","Dashboard")" class="btn btn-sm btn-danger"><i class="fa fa-ban"></i> انصراف</a>
            <button type="button" class="btn btn-sm btn-primary" onclick="AddPostBlog();"><i class="fa fa-dot-circle-o"></i> ثبت خبر</button>
        </div>
    </div>
    <div id="blogimageShow">

    </div>
</div>

When the user enters all his information (most notably the photo), Click on the button with Onclick="AddPostBlog();" clicks.

When a button is clicked, a function is called.

This is my function :

function AddPostBlog() {

var myAdminBlog = {
    BlogTitle: $("#BlogTitle").val(),
    BlogShortDesc: $("#BlogShortDesc").val(),
    BlogLongDesc: $("#BlogLongDesc").val(),
    BlogView: CheckBlogView(),
    BlogFire: CheckBlogFire(),
    BlogCommentEnable: CheckBlogCommentEnable(),
    BlogDatePublish: $("#BlogDatePublish").val(),
    BlogImage: $("#BlogImage").val(),
    BlogReview: $("#BlogReview").val(),
    BlogPublisher: $("#BlogPublisher").val(),
    PostCategory3: $("#PostCategory3").val(),
    BlogKeywords: $("#tags").val(),
    File: $("#BlogImage").val()
};

$.ajax({
    url: 'AddPostBlog',
    data: JSON.stringify(myAdminBlog),
    type: "POST",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function (errormessage) {
        alert(errormessage);
    }
});

Check the latest JSON file object(File: $("#BlogImage").val()). That is my photo file. This function is referred to the AddPostBlog controller.

Before you see the controller code, first see my Model Code.

 public class csAdminBlog
{
    public int BlogID { get; set; }

    public string BlogTitle { get; set; }

    public string BlogShortDesc { get; set; }

    public string BlogLongDesc { get; set; }

    public string BlogDatePublish { get; set; }

    public string BlogImage { get; set; }

    public bool BlogView { get; set; }

    public bool BlogFire { get; set; }

    public int BlogRate { get; set; }

    public int BlogReview { get; set; }

    public bool BlogCommentEnable { get; set; }

    public string BlogKeywords { get; set; }

    public int BlogCategory3ID { get; set; }

    public string BlogCategory3Title { get; set; }

    public bool BlogCategory3View { get; set; }

    public int BlogCategory2ID { get; set; }

    public string BlogCategory2Title { get; set; }

    public bool BlogCategory2View { get; set; }

    public int BlogCategory1ID { get; set; }

    public string BlogCategory1Title { get; set; }

    public bool BlogCategory1View { get; set; }

    public int UserID { get; set; }

    public string UserName { get; set; }

    [DataType(DataType.Upload)]
    public HttpPostedFileBase File { get; set; }}

Look at the latest Property in the model.It's for taking photos and keeping it.

Now See My Controller Code :

The first action is to send complete data received from the user to the database and save the image on the server

public JsonResult AddPostBlog(csAdminBlog myAdminBlog)
    {
        csAdminBlog PublicAdminBlog = new csAdminBlog();
        string Message = string.Empty;
        int UploadMessage = UploadImage(myAdminBlog);
        if (UploadMessage == 3)
        {
            int Ret = PublicAdminBlog.AddPostBlog(myAdminBlog);
            if (Ret == 1)
            {
                Message = "پست با موفقیت ثبت شد و با موفقیت به نمایش در آمد.";
            }
            else if (Ret == 2)
            {
                Message = "پست با موفقیت ثبت شد. برای به نمایش درآمدن, پست را ادیت کنید.";
            }
            else
            {
                Message = "مشکلی پیش آمده است. لطفا بعدا تلاش فرمایید.";
            }
            return Json(Message, JsonRequestBehavior.AllowGet);
        }
        else if(UploadMessage == 1)
        {
            return Json("فایل ارسالی شما مخرب یا نادرست است.",JsonRequestBehavior.AllowGet);
        }
        else if (UploadMessage == 2)
        {
            return Json("پسوند فایل شما نادرست است. فقط پسوند های PNG / Jpeg / Gif قابل قبول است.", JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json("مشکلی در آپلود فایل پیش آمده است.", JsonRequestBehavior.AllowGet);
        }

    }

Now let's look at the second controller code that receives the photo and saves it on the server

Note : My main problem: the address of the photo is sent to the controller, but the photo itself is not sent

This is My Controller Code UploadImage :

public int UploadImage(csAdminBlog myAdminBlog)
    {

        string[] ValidImageTypes = new string[]
        {
            "image/gif",
            "image/png",
            "image/jpeg",
            "image/jpg",
            "image/pjpeg"
        };

        try
        {
            if (myAdminBlog.File == null || myAdminBlog.File.ContentLength == 0)
            {
                return 1;
            }
            else if (!ValidImageTypes.Contains(myAdminBlog.File.ContentType))
            {
                return 2;
            }

            if (myAdminBlog.File != null && myAdminBlog.File.ContentLength > 0)
            {
                myAdminBlog.File.SaveAs(Path.Combine(Server.MapPath(ExynosCRUD.PathBlog), myAdminBlog.File.FileName));
                myAdminBlog.BlogImage = Path.Combine(Server.MapPath(ExynosCRUD.PathBlog), myAdminBlog.File.FileName);
                return 3;
            }
            else
            {
                return 4;
            }


        }
        catch (Exception Err)
        {
            throw;
        }
    }

Finally, tell me why the photo is not sent to the desired property and its data is Null

  • Use `FormData` and set the correct ajax options - refer [How to append whole set of model to formdata and obtain it in MVC](https://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Oct 13 '18 at 10:21
  • @StephenMuecke Hello my friend . I did all this. I've even changed AJAX code several times but failed.Identifies the photo's address well, but does not send the photo. – Programmer Oct 13 '18 at 10:33
  • Then you obviously did it wrong (and I cannot guess what code you tried) –  Oct 13 '18 at 10:34
  • And I suggest you go to the mvc site and work through some tutorials to learn the basics - especially how to generate a view using the strong typed `HtmlHelper` methods and bind to your model –  Oct 13 '18 at 10:37
  • @StephenMuecke i try to send the photo to the controller parameter, but I can not – Programmer Oct 13 '18 at 10:38
  • Read the link I gave you! –  Oct 13 '18 at 10:39

1 Answers1

0

Useing FormData() Js Function.After that passing this formData by your ajax. May be this will help for you.

    var formData = new FormData();
    formData.append("File", document.getElementById("BlogImage").files[0]);
zaman
  • 145
  • 7