Refresh the screen with modifications from the Model using Ajax Post through a javascript function

I am using Ajax to update the model value in my application and I need help showing this new value in the view. Below is the code snippet where I call a method called GetText to update the model value. How can I display the updated model value in the HTML file? Your assistance would be greatly appreciated.

public class EmpModel
{
public string EmpClaim {get;set;}
}


 public IActionResult EmpClaim()
 {
    return View();
 }
 [HttpPost]
    public ActionResult GetText(EmpModel model)
    {
        model.EmpClaim = "New Text" // This should be shown in view

         return Json(data);

    }

Html file

@model Test.Models.EmpModel
<div>
<input type="text" name="Claim" class="form-control" id="TxtClaim"  asp-for="Claim" data-role="text"/>
</div>

<div>
    <input type="button" onclick="changeText()" id="changeButton"  />
</div>

Javascript

<script>
 function changeText()
{
 var url = '@Url.Action("GetText", "EmpDoc")';
    $.post(url, $('form').serialize(), function (view) {
        $("#TxtClaim").val(); // How can I update the TxtClim with model.EmpClaim "New Text" 
    });
}

</script>

Answer №1

To send a string back to an ajax function, you can utilize return Content().

    [HttpPost]
    public IActionResult GetText(EmpModel model)
    { 
       model.EmpClaim = "New Text"; // This text should be displayed in the view  
        return Content(model.EmpClaim); 
    }

Javascript:

 <script>
     function changeText()
     {
     var url = '@Url.Action("GetText", "EmpDoc")';
        $.post(url, $('form').serialize(), function (view) {
            $("#TxtClaim").val(view); // How do I update TxtClaim with the new text from model.EmpClaim?
        });
    }
    </script>

Check out the result here: https://i.sstatic.net/lUR8m.gif

Note:

In this scenario, your model lacks a key field, making it difficult to pinpoint which data to update when making changes. You may need to reconsider the design of your model for future operations.

You may find more information on creating and editing views in ASP.NET MVC here.

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

Steps for retrieving a table of records with Jquery and sending it to the server through AJAX

Displayed below is a table I have: <table cellspacing="0" rules="all" border="1" id="ContentPlaceHolder1_GridView1" style="border-collapse:collapse;" class="table table-striped"> <tbody> <tr> <th scope="col"> ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Leveraging Underscore in ReactJS applications

I'm encountering an issue with integrating Underscore into my ReactJS project. When I attempt to run my ReactJS class, the following error arises: Uncaught ReferenceError: _ is not defined index.html <html> <head> <meta http-equi ...

Menu rollout problem when clicking or hovering

I'm facing challenges in making my menu content appear when a user clicks or hovers over the hamburger menu. My app is built using Angular, and I've written some inline JavaScript and CSS to achieve this, but the results are not as expected. Here ...

Task: Convert SQL query results from XML to JSON format using Logic App

I have encountered an issue with my SQL query that returns XML data in SQL Server using For XML. When I run the query (Execute a SQL Query) in Logic Apps, it converts the XML into JSON format. My goal is to send this XML data to a Dynamics 365 integration ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

Search through an array of objects and assign a new value

I am facing a challenge with an array of objects structured as shown below: [ { "e_id": "1", "total": 0 }, { "e_id": "3", "total": 0 } ] My objecti ...

The target for CountUp is not defined in React.js and is either null or undefined

I'm experiencing an issue with React.js while using the CountUp library. I've tried everything I can think of, but so far, nothing has worked. I even created a state to check if the component is ready to render CountUp. I'm unsure whether t ...

Exploring how Node.js, Express.js, and Mongoose work together to handle

I am experiencing difficulties with handling data received from APIs, as it returns null and doesn't wait even though I have used async/await functions. My goal is to retrieve data from the first URL, then gather data from other URLs based on the res ...

a guide on monitoring the status of a stripe transaction through a straightforward form and javascript

Currently, I am in the process of setting up Stripe checkout for my website. I have successfully implemented the payment form, but now I need to figure out how to redirect the user to another page after a successful payment. Below is the JavaScript code th ...

The second div element remains unselected in jQuery

Below is the example of an HTML structure: <span id="17">yes here</span> <div class="PricevariantModification vm-nodisplay"></div> <div class="PricesalesPrice vm-display vm-price-value"> <span class="a"></span> ...

Turn JSON logic into an Elasticsearch query

Prior to dedicating time to constructing this tool, I am curious if anyone has developed or is familiar with a conversion tool that can convert jsonlogic (jsonlogic.com) into an elasticsearch query dsl format. Appreciate any insights! ...

Unlocking the Secrets of Launching a Modal with Javascript

I currently have an HTML code that includes a fabulous floating button. When I click on this button, I would like to open a modal popup window but unfortunately, I am unsure of how to achieve this. index.html <html> <head> <link rel="s ...

The function is invoked numerous times

My issue involves using jQuery to handle the mouseenter and mouseleave events. The problem arises when transitioning from one div to another, causing the events to trigger again. I am looking for a solution to only run these events once per mouse enter and ...

Is it possible for me to transfer a class attribute to a directive template in AngularJS?

I recently came across this directive in AngularJS: productApp.directive('notification', function($timeout) { return { restrict : 'E', replace : true, scope : { type: "@", message: "@ ...

What is preventing me from being able to spyOn() specific functions within an injected service?

Currently, I am in the process of testing a component that involves calling multiple services. To simulate fake function calls, I have been injecting services and utilizing spyOn(). However, I encountered an issue where calling a specific function on one ...

I am receiving an error stating "Page not found" when making an AJAX request. What could be causing

Whenever I attempt a POST request, I consistently receive the 'Requested page not found. [404]' error message. I am unable to identify the root cause of this issue, so please provide your guidance and advice. I have developed a web API using ASP ...

Leveraging environmental variables in a Vue.js web application

The article I recently came across discussed how to effectively utilize environment variables in vuejs. Following the instructions, I set up my local .env.local file and also installed dotenv. VUE_APP_AUTH_AUTHORITY = 'http://localhost/auth' I ...