What is the best way to send a ViewModel property to an ajax post function?

 function ResendEmailInvite(internalUserId, familyMemberId) { 
       theinternalUserId = internalUserId;
       theFamilyMemberId = familyMemberId;
      if(confirm('Are you sure you want to resend this family member's invite?')){
         $.ajax({
             type: "POST",
             url:"/Admin/ResendFamilyMemberEmail",
             data: {internalUserId : theinternalUserId, familyMemberId : theFamilyMemberId}, 
             success: function(response){
                alert(response);
             },
             error: function(){
                alert("Error");
            }
        });
        return false;
    }
}

I am utilizing ASP.net MVC 3. This code represents an ajax/javascript method within my view.

In terms of syntax correctness, is there anything wrong with it as far as you can tell?

The value for familyMemberId will be variable, while the userId will remain constant. I aim to pass the userId from my viewModel to this ajax call, what is the best way to achieve this?

Answer №1

If you're looking to transfer data from the model in your controller to the view, that's what MVC is designed for. According to the MSDN MVC 4 Tutorial:

Controller:

To define your model, you can use the VS menu system and Entity Framework to access the database.

 public class YourController : Controller
{
     private YourDBContext db = new YourDBContext();

     public ActionResult YourAction(int user_id = 0)
    {
        User user = db.Users.find(user_id);
        if(user == null) {
           return HttpNotFound(); // Or unauthorized or whatever
        }
        return View(user);
    }
    //...

View:

@Model IEnumerable<MvcUser.Models.User>

<!-- other stuff -->

 <script type="text/javascript>
 // the rest of your script
        function ResendEmailInvite(internalUserId, familyMemberId) { 
           theinternalUserId = @Model.userId;
           theFamilyMemberId = familyMemberId;
          if(confirm('Are you sure you want to resend this family member's invite?')){
             $.ajax({
                 type: "POST",
                 url:"/Admin/ResendFamilyMemberEmail",
                 data: {internalUserId : theinternalUserId, familyMemberId : theFamilyMemberId}, 
                 success: function(response){
                    alert(response);
                 },
                 error: function(){
                    alert("Error");
                }
            });
            return false;
        }
    }

This method works because, as mentioned, the userId remains static after the page loads. For more dynamic behavior, you'd need another HTML hook for javascript to utilize.

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

Why does jQuery ajaxSend() function work in Firefox but not in Chrome?

The script works perfectly in Firefox but encounters issues in Chrome. sendRequest(); triggers a $.ajax() request. sendRequest('post') $('#status').ajaxSend(function() { $(this).removeClass(); $(this).html('Posting...'); ...

The replace method for strings in JavaScript does not function properly on mobile devices

I encountered an issue with the string replace method I implemented on my website. Upon checking the page using the web browser on my Android phone, I noticed that it was not functioning as intended. Here's a snippet of the code: /*The function is ...

Enhancing User Interfaces with JQuery UI Widgets and Dynamic AJAX Calls

Currently involved in geolocation and mapping work, I am creating a JQuery widget to ensure that the code is portable for future projects. However, I have hit a roadblock when it comes to making an AJAX request. Below are a couple of methods from my widge ...

Updating the background color of several tags with jQuery

<rect class="day" fill="#fbedf0" data-count="0"></rect> <rect class="day" fill="#cqe45b" data-count="0"></rect> I am attempting to modify the fill color values of multiple rect tags using jQuery. While I can successfully loop thro ...

Merging object keys and values from JSON arrays based on their keys, using JavaScript

Is there a way to merge object keys' values from JSON arrays based on their key? json1 = [ {key:'xyz', value:['a','b']}, {key:'pqrs', value:['x','y']} ] json2 = ...

Creating images or PDFs from HTML with CSS filters: a guide

Looking for someone who has experience creating images or PDFs from HTML code. The HTML contains images with CSS filters such as sepia and grayscale. If you have worked on this type of project before, I would love to hear about your experience. <img cl ...

Can WikiData be accessed by providing a random pageId?

My current project involves creating a Wikipedia Search App with a 'Feel Lucky' button. I have been trying to figure out if it's possible to send a request for Wikidata using a specific pageid, similar to the code below: async function lucky ...

Ensure that the <a> tag contains an absolute URL, disregarding the base URL

When working with my Angular app, I have set <base href="/foo/bar/"> and enabled html5 mode using $locationProvider.html5Mode(true); Now, I want to generate a list that looks like this: <div ng-repeat="item in vm.items"> <a ng-href="{{it ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Substitute approach for Marionette driver action class

Previously, I had code to draw a rectangle in Selenium WebDriver which worked fine. However, after switching to Marionette driver, it stopped working because the Action class is not supported. I am looking for an alternative solution similar to using the R ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...

Use the ReturnFormat row parameter while submitting a CFAJAX request via POST

I'm encountering issues with implementing the setQueryFormat() function in an AJAX call in CF9. My CFM file has the following structure: <div id="div1" onclick="callfkt1('POST');" style="cursor:pointer;">POST</div> <div i ...

What could be the reason for the GET request not functioning properly in Node.js?

const express = require('express'); const mongoose = require ("mongoose"); const app = express(); const Student = require('../models/students'); require('dotenv').config(); const PORT = process.env.PORT || 3000; const co ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Enhancing a Pie Chart Dynamically with Ajax using Highcharts

I need assistance with updating the data for the pie chart when a list item is clicked. The issue arises when using dynamic values from $cid in data.php. For example, user_student.cid = 1 works correctly, but if I use user_student.cid = $cid, it doesn&apos ...

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

Switch out the innerHTML content and then revert back to the original while still preserving the events

Imagine you have a div called el with various components and events that are out of your control (like on mouse over and click). What if you wanted to insert a new widget inside this div? You might try something like this: var save = el.innerHTML; el.inn ...

"Why is the action.js section showing as undefined?

I'm facing an issue with the action.js file where I keep getting undefined as a response from the service. However, when I debug the service.js API function, it shows the correct response. Here is the code snippet for better understanding: Action.js ...