Return View and JSON data at same time from Controller in ASP.Net MVC

SajidHussa
 
on Aug 06, 2021 01:10 AM
Sample_119440.zip
519 Views

there are two method 

one is Action Result StudyMaterial, second is JsonResult getchapter()

both method worh on page load 

can i bind this two method in one method

can i return view and json data both 

like

return view("index", mylist,JsonRequestBehavior.AllowGet)

public ActionResult StudyMaterial()
{
    return View();
}
 
public JsonResult getchapter()
{
 
    string courseid = Session["courseid"].ToString();
    string subjectid = Session["courseid"].ToString();
    
        List<SelectListItem> myList = new List<SelectListItem>();
        DataTable dt = new DataTable();
        try
        {
        string query = "usp_tbl_topic";
        using (SqlConnection con = Connection.getConnection())
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.Clear();
                con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@courseid", SqlDbType.NVarChar).Value = courseid;
                cmd.Parameters.AddWithValue("@subjectid", SqlDbType.NVarChar).Value = subjectid;
                cmd.Parameters.AddWithValue("@flag", SqlDbType.NVarChar).Value = "Z";
                SqlDataAdapter sdr = new SqlDataAdapter(cmd);
                sdr.Fill(dt);
                cmd.Connection = con;
                con.Close();
            }
        }
      
        foreach (DataRow dtRow in dt.Rows)
        {
            //foreach(DataColumn dc in dtRow)
 
            myList.Add(new SelectListItem
            {
                Text = dtRow["chaptername"].ToString(),
                Value = dtRow["chapterid"].ToString(),
            });
        }               
    }
    catch(Exception ex)
    {
       
    }
    return Json(myList, JsonRequestBehavior.AllowGet);
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 06, 2021 01:30 AM

Hi SajidHussa,

Check this example. Now please take its reference and correct your code.

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        List<SelectListItem> customers = new List<SelectListItem>();
        customers.Add(new SelectListItem { Text = "John Hammond", Value = "1" });
        customers.Add(new SelectListItem { Text = "Mudassar Khan", Value = "2" });
        customers.Add(new SelectListItem { Text = "Suzanne Mathews", Value = "3" });
        customers.Add(new SelectListItem { Text = "Robert Schidner", Value = "4" });
        return View(customers);
    }

    public JsonResult getchapter()
    {
        List<SelectListItem> myList = new List<SelectListItem>();
        myList.Add(new SelectListItem { Text = "Chapter 1", Value = "1" });
        myList.Add(new SelectListItem { Text = "Chapter 2", Value = "2" });
        myList.Add(new SelectListItem { Text = "Chapter 3", Value = "3" });
        myList.Add(new SelectListItem { Text = "Chapter 4", Value = "4" });
        return Json(myList, JsonRequestBehavior.AllowGet);
    }
}

View

@model List<SelectListItem>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                url: "/Home/getchapter",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (chapters) {
                    var row = "";
                    $.each(chapters, function () {
                        row += "<tr><td>" + this.Text + "</td></tr>";
                    });
                    $('#tblChapter tbody').append(row);
                }
            });
        });
    </script>
</head>
<body>
    <table>
        <tr>
            <th>Name</th>
        </tr>
        @foreach (SelectListItem item in Model)
        {
            <tr>
                <td>@item.Text</td>
            </tr>
        }
    </table>
    <hr />
    <table id="tblChapter">
        <thead>
            <tr>
                <th>Name</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</body>
</html>

Screenshot

dharmendr
 
on Aug 06, 2021 05:23 AM

Instead of creating another JsonResult inside the view convert the List to Json and save in ViewData or Session.

Then return to the specified View and use the ViewData or Session.