Leveraging a partial view across two different perspectives

I am working with a PartialView that is used in two different views, each utilizing its own viewmodel. On one of the views, the code looks like this:

view1:

@model StudentsViewModel
......
.....
@Html.Partial("_StudentOtherInformation")

PartialView

@model StudentsViewModel
@if (Model.StudentList != null)
{
<input type="hidden" id="firstStudent" value= "@Model.StudentList.ElementAt(k-1).StudentID" />
}

view2:

@model SearchViewModel
....
@Html.Partial("_StudentOtherInformation")

When trying to access the viewmodel of view1 within the partial view, I encountered an exception due to confusion between viewmodels. After some research, it seems creating a parent viewmodel containing both individual viewmodels is one solution. However, the challenge lies in the fact that these two viewmodels are in separate namespaces. Is there a way to pass the corresponding viewmodel to the partial view from each of the views?

Answer №1

If you want to pass your ViewModel as the second argument, you can do so by following these steps:

Example for view1:

@model StudentsViewModel
......
.....
@Html.Partial("_StudentOtherInformation", model)

Example for view2:

@model SearchViewModel
....
@Html.Partial("_StudentOtherInformation", model)

Keep in mind that this method doesn't work if you need to pass two different types of ViewModels.

One solution is to create a base class where you place all common properties, and then have your two ViewModels inherit from this base class. It's perfectly fine if they are in different namespaces; just ensure you reference the correct namespaces like this:

public class ParentViewModel
{
    public List<Student> StudentList { get; set; }
}

public class StudentsViewModel : YourNamespace.ParentViewModel
{
     // other properties here
}

public class SearchViewModel: YourNamespace.ParentViewModel
{
     // other properties here
}

Make sure that your partial view is strongly typed to the base-class like this:

Partial View

@model ParentViewModel
@if (Model.StudentList != null)
{
<input type="hidden" id="firstStudent" value= "@Model.StudentList.ElementAt(k-1).StudentID" />
}

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

Utilize jQuery to automatically generate a file path using the unique identifier of a link that is clicked by users

I am currently working on developing a system that dynamically generates paths to specific JSON files upon clicking various links. This is specifically for a restaurant menu display. The goal is to have the JSON data returned and parsed into HTML within a ...

Guide to releasing an independent Angular component (njsproj) alongside a web application using Visual Studio 2017

We are in need of publishing our website locally to test it on Sitecore. Our special component for this purpose is called webapp. Recently, we introduced a new component (njsproj file) that contains our Angular application. However, when I publish webapp, ...

Can Javascript execute an OR statement?

I am trying to filter an array where the parameters can be "true", "false", or "true || false". I am struggling to find a way to retrieve the "true || false" part. Is it feasible? Below is the code for filtering the array: const filtered = data.filter(ent ...

Making a jQuery AJAX request for JSON from a separate domain

My goal is to send an AJAX request to , expecting JSON data in return (not sure if JSONP) However, when I click on the button to make the AJAX request, I encounter this issue: http://prntscr.com/8xswr1 (Google Chrome Console) Upon double-clicking ' ...

Introducing the serverRuntime tag in the webconfig results in a 500.19 error

After downloading an asp.net project from TFS onto my other laptop, I encountered difficulties running it. Upon further investigation, the issue seems to be related to the webconfig setting: <serverRuntime uploadReadAheadSize="128000000" /> ...

Issue opening react modal dialogue box

I'm encountering an issue while trying to implement the headless ui modal. I'm attempting to trigger the modal.js script from my home.js file. In my home.js file, I have the following code snippet: function Home() { const [isOpen, setIsOpen] = ...

What steps are involved in generating JSONP from an external JSON source?

I have a dilemma with two different domains: www.domain1.com and www.domain2.com Domain1 hosts a simple JSON feed. My goal is to retrieve the JSON feed from domain1 and display it in a module on domain2. After some research, I've come across sugges ...

Resolve issues with vue js checkbox filtering

As I embark on my Vue journey, I came across some insightful queries like this one regarding filtering with the help of computed(). While I believe I'm moving in the right direction to tackle my issue, the solution has been elusive so far. On my web ...

How is it possible for this code to function when the object is not explicitly defined within the javascript code?

While using JSLint, I encountered an issue where it stated: 'matte_canvas' is not defined. Although I have not explicitly defined 'matte_canvas' in my javascript code, it does output the canvas element in the console. Below is the code ...

Fix Problem: Object reference not initialized

I encountered an issue while attempting to upload an image file using FileUpload. The error occurs when the button is clicked for insertion. public int InsertData(ProductPhoto prdctphoto) { int ans = 0; SqlCommand cmd = D ...

How can we use React.js to redirect upon submitting a form?

Hello everyone. I've created an app where users can create posts. As the owner of a post, you have the ability to delete it by clicking on a delete button, which triggers a modal to confirm deletion. However, I'm facing an issue with redirecting ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

The router.get function seems to be malfunctioning, however when using the router.get function with an id

When I call http://localhost:5000/surveycreate/4, it successfully redirects me to the surveypage.html page. However, calling http://localhost:5000/surveycreate does not work as expected. Instead of redirecting me, it leads me back to my main index.js file ...

The elements in Dynamically generated ChartJs do not align with the bottom of the y-axis

I'm experiencing some unusual behavior with bars or risers in a dynamically generated Chartjs chart. They are not starting at point 0 on the y-axis and some of them are not displaying at all. Despite trying various solutions from different sources, i ...

Can props be updated or declared as a variable in order to render a sub-component within a child component in NextJS?

I have created a parent and child component named RightFrame. I would like to display different components within the child by updating its state with props. However, I also want the child component to be able to update its own state (currently passed as p ...

Utilizing Node.js: How to access another function within the same controller?

I am facing an issue with accessing one function from another in my code. How can I achieve this? class firstController { firstFunction(req, res) { var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(n ...

Ways to improve the performance of a slow ASP.NET page by caching multiple datasets

I am experiencing slow loading times on my page. I am fetching data from two large dataviews to populate a table with sales history information based on yesterday's sales/numbers. I am considering caching the data, but I'm unsure how to handle it ...

Utilize nodejs and expressjs to send a file to a server using a URL

Seeking guidance on how to POST a file URL to my express app and download the file onto my own server. For instance, I have a list of images sourced from a third-party platform. When a user clicks on the download button, a post request needs to be sent to ...

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

What is the best way to use spies to test my asynchronous code in Jasmine with Node.js Promises?

In my simplified example module called process-promise, there is a single function that takes a Promise as input and processes it by calling other functions from external modules. Here is the code snippet for the processPromise function: //<process-pro ...