使用单个ajax请求呈现json数据和部分视图。

时间:2022-10-08 16:28:07

Code given below sends an ajax request to the controller.

下面给出的代码向控制器发送ajax请求。

 if (btid === '01') {
                var allData = {
                    "sessionName": $('#sessionname').val(),
                    "foundStudent": $('#studentId').val(),
                    "code":btid
                }
                var mySession = JSON.stringify(allData);
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("RenderView", "ManualFeesCollection")',
                    contentType: "application/json; charset=utf-8",
                    data: mySession,
                    success: function (data) {
                          $('#maindiv').html('')
                          $('#maindiv').html(data)
                          $.each(data.myMonths, function (index, item) {
                           //Here I want to access myMonths as Json
                        })
                    },
                })

Below in the Controller Action.

下面的控制器动作。

public ActionResult RenderView(int code,long foundStudent,int sessionName)
        {
            var months = //get some months
            var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        });// Want access this data in ajax success function
            return PartialView("MonthwiseFees",myMonths);

    }

But the problem is I am getting the view in the #maindiv,but not not getting

但是问题是我在#maindiv中获得了视图,但是没有得到

myMonths

myMonths

as json, in the success function of ajax. I need to do something in view with those myMonths.Currently I am sending two ajax request(in the success of another) to accomplish.But I wish I could do it with a single ajax request.Thanks for spending time on my Issue.

作为json,在ajax的成功函数中。在这几个月里,我需要做点什么。目前我正在发送两个ajax请求(另一个请求成功)以完成。但是我希望我可以用一个ajax请求来完成它。谢谢你花时间讨论我的问题。

  • Update1: code of partial view

    Update1:部分视图的代码

    {
    
    <tr>
        <td>
         @x
        </td>
        <td>
          @months[no]
        </td>
        <td>
            @Html.CheckBox(" " + @x, new { @class="check",id="check"})
            @Html.Label(" ", new { @class="lbl"})
         </td>
    </tr>
    x = x + 1;
    

    }

    }

                 <input type="button" class="mybutton btn btn-small btn-primary" value="Show >"/>
    
            </div>
        <div class="span7" id="classwiseheads">
            </div>
    </div>
    

3 个解决方案

#1


2  

You cannot send text/html and application/json for a single request. You could send either one.

不能为单个请求发送文本/html和应用程序/json。你可以随便送一个。

If you are returning PartialView from controller, then the content type will be set to text/html. But still you can render the JSON as part of partial view.

如果从controller返回PartialView,那么内容类型将设置为文本/html。但仍然可以将JSON作为部分视图的一部分呈现。

public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });
        ViewBag.Months=myMonths;
    return PartialView("MonthwiseFees");

}

Then in your partial view

那么在你的部分观点中

<script>
var myJSArray=@Html.Raw(JSON.Encode(ViewBag.Months)
</script>

jQuery

jQuery

success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(myJSArray, function(index, item) {
        //myJSArray will be available in window scope now
    })
}

Update: Based on updated question

更新:基于更新的问题

Controller

控制器

public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });        
    return PartialView("MonthwiseFees",myMonths);

}

This will check all the check boxes as I pass true for Html.CheckBox. This needs to be determined with the model and months array

当我为Html.CheckBox传递true时,将检查所有复选框。这需要用模型和月数组来确定。

@model List<string>

@using System.Globalization;

@{

    Layout = null;
    string[] months =DateTimeFormatInfo.CurrentInfo.MonthNames;
    var countMonths=months.Count();
    int x = 1;
}
<div>

@for (int no=0;no<countMonths-1;no++)
{

    <tr>
        <td>
         @x
        </td>
        <td>
          @months[no]
        </td>
        <td>
            //determine true/false by comparing months and Model
            @Html.CheckBox(" " + @x, model.Contains(months[x]), new { @class="check",id="check"})           
         </td>
    </tr>
    x = x + 1;
}
</div>

jQuery

jQuery

success: function(data) {
    $('#maindiv').html('');
    $('#maindiv').html(data);        
}

#2


1  

Lets start with your following code

让我们从下面的代码开始。

var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        });

Here I am assuming your myMonths gets filled with a list of integers. I suggest adding a .ToList(); to the above code. So now it becomes :

这里我假设您的myMonths中包含了一个整数列表。我建议添加.ToList();上面的代码。现在它变成:

var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        }).ToList();

Now let's check your jquery code, your ajax's success method look like this

现在让我们检查一下jquery代码,您的ajax成功方法如下所示

success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(data.myMonths, function(index, item) {
        //Here I want to access myMonths as Json
    })
}

Here you write $('#maindiv').html(data), data here is a collection of integers (collection of months), .html() wont work that way.

在这里,您可以编写$('#maindiv').html(数据),这里的数据是整数集合(收集月份),.html()不是这样工作的。

Now since you are using this ajax call to get the JSON values only. I don't see the need to return a Partial View for that. Your return statement from your action could look like :

现在,由于您使用这个ajax调用只获取JSON值。我不认为有必要对此进行部分的解释。你的行动回覆陈述可以如下:

return Json(myMonths, JsonRequestBehavior.AllowGet);

and now when you use the following jquery, you will be able to access each month as required:

现在,当您使用以下jquery时,您将能够按需要访问每个月:

$.each(data, function(index, item) {
    // here is your month in the 'item' variable.
    $('#maindiv').html(item)
})

Update 1:

I see you are trying to load your partial view using an ajax call and then also use the data returned in that ajax call.

我看到您尝试使用ajax调用加载您的部分视图,然后使用ajax调用返回的数据。

Why dont you load your partial view using the @Html.Partial or @Html.Action (how to). And ideally that partial view should have a call to your action which return JSON data which then you could use accordingly.

为什么不使用@Html加载部分视图呢?部分或@Html。行动(如何)。理想情况下,部分视图应该对动作进行调用,返回JSON数据,然后您可以相应地使用这些数据。

Update 2:

Your latest comment says

你的最新评论说

One page load I don't need that view.I need that view on some button clicked.

一个页面装载,我不需要那个视图。我需要点击某个按钮的视图。

This could be helpful : https://*.com/a/11964905/1182982

这可能有帮助:https://*.com/a/11964905/1182982

#3


0  

Thanks goes to Murali Murugesan and yasser for help

感谢Murali Murugesan和yasser的帮助

I used the concept of Murali Murugesan by sending necessary data the in ViewBag.But since my partial view is Not Strongly Typed ,for this reason I needed to use javascript.

我使用Murali Murugesan的概念,将必要的数据发送到ViewBag中。但是由于我的部分视图不是强类型的,因此我需要使用javascript。

I edited my controller Action like below

我编辑了我的控制器动作如下所示

var months = fcDetailsService.GetStudentWiseCollectionDetail(foundStudent, sessionName, "01");
            var data = (from w in months
                        select new
                        {
                            w.Month

                        });
            ViewBag.Months = JsonConvert.SerializeObject(data);
            if (data != null)
            {
                return PartialView("MonthwiseFees", data);
            }
            else
                return Json("MonthwiseFees");

Then in my javascript, I did below

然后在我的javascript中,我在下面做了

$(function () {
        var i = 0;
        var myarray = new Array();
        myarray =@Html.Raw(@ViewBag.Months)
            $('.check').each(function () {
                for (var x = 0; x < myarray.length; x++)
                {
                        var me = (JSON.stringify(myarray[x].Month))
                        if ($.trim(this.name) === $.trim(me)) {
                            $(this).prop("checked", true)
                            $(this).attr("disabled", true)
                            return true;
                    }
                }
            });
    });

#1


2  

You cannot send text/html and application/json for a single request. You could send either one.

不能为单个请求发送文本/html和应用程序/json。你可以随便送一个。

If you are returning PartialView from controller, then the content type will be set to text/html. But still you can render the JSON as part of partial view.

如果从controller返回PartialView,那么内容类型将设置为文本/html。但仍然可以将JSON作为部分视图的一部分呈现。

public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });
        ViewBag.Months=myMonths;
    return PartialView("MonthwiseFees");

}

Then in your partial view

那么在你的部分观点中

<script>
var myJSArray=@Html.Raw(JSON.Encode(ViewBag.Months)
</script>

jQuery

jQuery

success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(myJSArray, function(index, item) {
        //myJSArray will be available in window scope now
    })
}

Update: Based on updated question

更新:基于更新的问题

Controller

控制器

public ActionResult RenderView(int code,long foundStudent,int sessionName)
{
    var months = //get some months
    var myMonths= (from w in months
                select new
                {
                    w.Month
                });        
    return PartialView("MonthwiseFees",myMonths);

}

This will check all the check boxes as I pass true for Html.CheckBox. This needs to be determined with the model and months array

当我为Html.CheckBox传递true时,将检查所有复选框。这需要用模型和月数组来确定。

@model List<string>

@using System.Globalization;

@{

    Layout = null;
    string[] months =DateTimeFormatInfo.CurrentInfo.MonthNames;
    var countMonths=months.Count();
    int x = 1;
}
<div>

@for (int no=0;no<countMonths-1;no++)
{

    <tr>
        <td>
         @x
        </td>
        <td>
          @months[no]
        </td>
        <td>
            //determine true/false by comparing months and Model
            @Html.CheckBox(" " + @x, model.Contains(months[x]), new { @class="check",id="check"})           
         </td>
    </tr>
    x = x + 1;
}
</div>

jQuery

jQuery

success: function(data) {
    $('#maindiv').html('');
    $('#maindiv').html(data);        
}

#2


1  

Lets start with your following code

让我们从下面的代码开始。

var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        });

Here I am assuming your myMonths gets filled with a list of integers. I suggest adding a .ToList(); to the above code. So now it becomes :

这里我假设您的myMonths中包含了一个整数列表。我建议添加.ToList();上面的代码。现在它变成:

var myMonths= (from w in months
                        select new
                        {
                            w.Month
                        }).ToList();

Now let's check your jquery code, your ajax's success method look like this

现在让我们检查一下jquery代码,您的ajax成功方法如下所示

success: function(data) {
    $('#maindiv').html('')
    $('#maindiv').html(data)
    $.each(data.myMonths, function(index, item) {
        //Here I want to access myMonths as Json
    })
}

Here you write $('#maindiv').html(data), data here is a collection of integers (collection of months), .html() wont work that way.

在这里,您可以编写$('#maindiv').html(数据),这里的数据是整数集合(收集月份),.html()不是这样工作的。

Now since you are using this ajax call to get the JSON values only. I don't see the need to return a Partial View for that. Your return statement from your action could look like :

现在,由于您使用这个ajax调用只获取JSON值。我不认为有必要对此进行部分的解释。你的行动回覆陈述可以如下:

return Json(myMonths, JsonRequestBehavior.AllowGet);

and now when you use the following jquery, you will be able to access each month as required:

现在,当您使用以下jquery时,您将能够按需要访问每个月:

$.each(data, function(index, item) {
    // here is your month in the 'item' variable.
    $('#maindiv').html(item)
})

Update 1:

I see you are trying to load your partial view using an ajax call and then also use the data returned in that ajax call.

我看到您尝试使用ajax调用加载您的部分视图,然后使用ajax调用返回的数据。

Why dont you load your partial view using the @Html.Partial or @Html.Action (how to). And ideally that partial view should have a call to your action which return JSON data which then you could use accordingly.

为什么不使用@Html加载部分视图呢?部分或@Html。行动(如何)。理想情况下,部分视图应该对动作进行调用,返回JSON数据,然后您可以相应地使用这些数据。

Update 2:

Your latest comment says

你的最新评论说

One page load I don't need that view.I need that view on some button clicked.

一个页面装载,我不需要那个视图。我需要点击某个按钮的视图。

This could be helpful : https://*.com/a/11964905/1182982

这可能有帮助:https://*.com/a/11964905/1182982

#3


0  

Thanks goes to Murali Murugesan and yasser for help

感谢Murali Murugesan和yasser的帮助

I used the concept of Murali Murugesan by sending necessary data the in ViewBag.But since my partial view is Not Strongly Typed ,for this reason I needed to use javascript.

我使用Murali Murugesan的概念,将必要的数据发送到ViewBag中。但是由于我的部分视图不是强类型的,因此我需要使用javascript。

I edited my controller Action like below

我编辑了我的控制器动作如下所示

var months = fcDetailsService.GetStudentWiseCollectionDetail(foundStudent, sessionName, "01");
            var data = (from w in months
                        select new
                        {
                            w.Month

                        });
            ViewBag.Months = JsonConvert.SerializeObject(data);
            if (data != null)
            {
                return PartialView("MonthwiseFees", data);
            }
            else
                return Json("MonthwiseFees");

Then in my javascript, I did below

然后在我的javascript中,我在下面做了

$(function () {
        var i = 0;
        var myarray = new Array();
        myarray =@Html.Raw(@ViewBag.Months)
            $('.check').each(function () {
                for (var x = 0; x < myarray.length; x++)
                {
                        var me = (JSON.stringify(myarray[x].Month))
                        if ($.trim(this.name) === $.trim(me)) {
                            $(this).prop("checked", true)
                            $(this).attr("disabled", true)
                            return true;
                    }
                }
            });
    });