Can JavaScript be incorporated into a Partial View in ASP.NET MVC?

I am diving into the world of .NET MVC and StackOverFlow, fully aware that my approach may not be conventional. However, I find myself a bit puzzled by the situation at hand.

Here's the scenario: I have three partial views each with their own model, all being rendered within a complete view. The complete view has a model that encompasses the three models from the partial views. One specific partial view includes a form which needs to execute an ajax request and send data to the main controller of the complete view in order to trigger an action.

The issue arises when everything is rendered on the main page, but I struggle to retrieve the necessary data from the model of the partial view. Even if I use a script in the main page, the required data seems to be missing. This problem leads me to raise the following question.

If you have any guidance or advice to offer, it would be greatly appreciated. I understand that the situation might seem a bit confusing, so please let me know if further clarification is needed.

Thank you.

Answer №1

If you want to achieve this task, here's how you can do it.

Let's say you have a model structured like this :

public class Book
    {
    [Key]
    public int ID { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }

}

Suppose you have a parent page named index and two partial views named LoadPartialView1 and LoadPartialView2 loading on that page.

You can use the code snippet

@Html.Action("LoadPartialView1", "Home")
to load the partial view. In this case, the LoadPartialView1 method in the Home controller will be called.

public class HomeController : Controller
    {
public PartialViewResult LoadPartialView1()
        {
            Book book = new Book()
            {
                ID = 1,
                Title = "Book1",
                Description = "Test",
                Price = Convert.ToDecimal(250.00)
            };
            return PartialView("_PartialView1", book);
        }
}

This example shows how the book model is passed to the partial view.

Now let's look at the contents of _PartialView1.

@model WebApplication1.Models.Book

<h4>This is the _PartialView1 Header</h4>
<p id="bookId">Book Id = @Model.ID</p>
<p>Book Title = @Model.Title</p>
<p>Book Descrittion = @Model.Description</p>
<p>Book Price = @Model.Price</p>

Next scenario - Suppose you need to submit a form. You can call the controller using an Ajax Call.

Loading _PartialView2 from controller as follows:

public PartialViewResult LoadPartialView2()
        {
            Book book = new Book();
            return PartialView("_PartialView2", book);
        }

Here's the content of my _PartialView2 :

@model WebApplication1.Models.Book

<h4>This is the _PartialView2 Header</h4>
<label>Book Id</label><input id="bookId" type="text" />
<label>Book Title</label><input id="bookName" type="text" />
<label>Book Descrittion</label><input id="bookDesc" type="text" />
<label>Book Price </label><input id="bookPrice" type="text" />
<input id="btnSave" type="button" value="Save"/>

<script type="text/javascript">

    $("#btnSave").click(function () {
        var id = $('#bookId').val();
        var name = $('#bookName').val();
        var desc = $('#bookDesc').val();
        var price = $('#bookPrice').val();

        var mybook = {
            ID: id,
            Title: name,
            Description: desc,
            Price: price

        };

        $.ajax({
            url: "/Home/DataFromPartialView",
            type: "POST",
            data: JSON.stringify(mybook),
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            error: function (xhr) {
                alert('Error');
            },
            success: function (result) {
                alert('Success');

            },
        });

    });

</script>

In this example, we extract data from the input fields, create a book object, and pass it to the DataFromPartialView method in the Home controller.

Below is the method implementation :

public PartialViewResult DataFromPartialView(Book mybook)
        {

            return View();
        }

By following these steps, you can successfully pass model data to the controller.

Lastly, here is the code for the Index Page which includes the partial views.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <div> 
        <p>This is my Home Page.</p>
    </div>
    <div id="partialView1">
       @Html.Action("LoadPartialView1", "Home")
    </div>
    <div id="partialView2">
        @Html.Action("LoadPartialView2", "Home")
    </div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only include unique objects in the array based on a common property

I am currently working with the following array: [ {name: "Mike", code: "ABC123"}, {name: "Sarah", code: "DEF456"}, {name: "John", code: "GHI789"}, {name: "Jane", code: "JKL01 ...

Having trouble positioning a div in AngularJS so that it stays pixel-perfect regardless of browser resize or device orientation? Unfortunately, it's

I am a newcomer to AngularJS and have been struggling with a particular issue for several days now, leading me to suspect that I may be using it incorrectly. The problem at hand involves positioning 30 divs in a specific manner: 1) Each div should displa ...

Having trouble retrieving JSON array in PHP

I'm facing a challenge accessing data from PHP that's coming from JSON in JavaScript. I utilize local storage to store some temporary information: var tbRomaneio = localStorage.getItem("tbRomaneio");// Retrieves stored data tbRomaneio = JSON.pa ...

Using JQuery to reveal a hidden child element within a parent element

I'm facing a challenge with displaying nested ul lists on my website. The parent ul is hidden with CSS, causing the child ul to also remain hidden even when I try to display it using jQuery. One approach I've attempted is adding a class to the f ...

What causes the inversion of height and width settings in react-webcam?

Currently utilizing react-webcam with the following configuration. <Webcam audio={false} screenshotFormat="image/jpeg" videoConstraints={{ facingMode: "environment", width: camera ...

What is the process of extracting a URL and inputting it into a form to enhance

Can anyone help with extracting a specific value (TEXT) from a URL and automatically paste it into an input form field? For example, if the URL is domain.com/page?code=123abc, I need to grab the code (in this case, 123abc) and have it automatically popula ...

Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties? Check out this method, but is it the most optimal solution? var obj = { 'a' : 'The foo ...

Whenever I attempt to log the retrieved data using console.log, it shows up as undefined initially. However, it eventually

One of the functions in my React app is used to fetch data from a Django API: const [filterData, setFilterData] = useState([]); const fetchFilterData = async () => { const filter_url = 'http://127.0.0.1:8000/api/filters/' try { ...

What are the steps to implement XML binding in GWT or JavaScript?

My objective is to implement XML binding in JavaScript, which may be considered unconventional. However, I require this functionality for a Thunderbird plugin and choosing JavaScript over XPCOM due to the lack of Java support in the latter. My goal is not ...

Starting a fresh SSH terminal directly from a web browser

I have an SSH IP address. Is it feasible to launch an SSH terminal through a web browser, similar to clicking on a hyperlink or Google Play store link? For instance: Click Here to Open SSH Terminal Upon clicking this link, the SSH session should open an ...

Exploring the features of NodeJS, diving into the world of mapping,

Currently, I am working in a Node.js environment and dealing with an array of IDs. My goal is to filter these IDs based on the response of another API call. Essentially, I need to check if each ID meets certain criteria specified by this external API. Whi ...

retrieving the current value of a variable from a jQuery function

I've done my best to keep things simple. Here's the HTML code I've put together: <div id="outsideCounter"><p></p></div> <div id="clickToAdd"><p>Click me</p></div> <div id="in ...

transferring selected dropdown list item from View to controller

By setting up a dropdown list in my view within the "Requests Table," I was able to successfully populate data from my database as an "Analysts list." Now, my challenge is figuring out how to pass the selected value from the dropdown list inside the table ...

Why are certain callback functions in my Node.js program not running asynchronously as expected?

I have a beginner question regarding the use of callbacks as a control flow pattern with Node and the http class. From what I understand about the event loop, all code is blocking, i/o is non-blocking, and by using callbacks. Here is an example of a simple ...

Why is my Typescript event preventDefault function ineffective?

Despite all my efforts, I am still unable to prevent the following a tag from refreshing the page every time it's clicked. <p> <a onClick={(e) => handleClick} href="&qu ...

Having trouble getting a value from a textbox to PHP using jQuery - can anyone lend a hand?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script> <input type="text" id= ...

Guide to extracting the values from a newly added table row with the onchange event

Seeking help for a complex issue I'm facing with my ajax function. The function retrieves data from a database and appends it to a table, sometimes resulting in multiple rows being appended due to multiple records retrieved. My challenge is extracting ...

Creating a 2D array in JavaScript filled with data retrieved from a PHP-MySQL database

Having just started learning Javascript/PHP, I have encountered a particular issue that I hope someone can assist me with. When attempting to generate a javascript array from PHP, everything works smoothly until I reach the column 'Function' in m ...

Display the heading of the current section in a stationary position on the side of the screen

On a single-page design, I would like the current section's heading to be fixed in place on the left side of the screen to indicate the user's location. This heading might also include an icon positioned to its left. My preference is for this flo ...

Picture Map Showing Icons Arranged in Active Spots

My project allows users to visualize an ImageMap with designated hotspots indicating printer locations in the office. Upon hovering over these hotspots, I plan to add a tooltip containing the printer name and offer the option to remotely install printer dr ...