Having issues with the onclick _dopostback function in MVC? It seems like the post

When attempting to execute a postback in ASP.NET MVC after confirming with JavaScript, the following button is used:

<input type="submit" id ="RemoveStatus" value="Remove Status" name="button" onclick="return CheckRemove();"/>

The JavaScript code for the CheckRemove() function is as follows:

var button1 = document.getElementById("RemoveStatus");

     if (confirm("Are you sure you want to remove status?") == true) 
                {
                    button1.disabled = true;
                    button1.value = "Removing status...";
                    __doPostBack('RemoveStatus', '');
                    return true;


                }
                else 
                {
                    return false;
                }

Despite setting the id and populating the button1 in debug, an "object expected" error is encountered at the __doPostBack function. I have attempted passing button1.id and button1 as arguments to __doPostBack, but the postback does not occur and the error persists. Any insights on resolving this issue would be greatly appreciated.

Answer №1

In MVC, postbacks are not used as they were in webforms. Instead, you can achieve the same effect by using nameoftheform.submit();.

For more information, visit:

To generate an id for the form tag, you can use the following code:

<% using (Html.BeginForm("Create", "Test", FormMethod.Post, new {id="myForm"})) {%>

Then, in your script, you can submit the form using:

document.getElementById('myForm').submit();

If you prefer using jQuery, you can achieve the same result with:

$('#myForm').submit();

Answer №2

Have you attempted to submit using jQuery in this manner?

$("#RemoveStatus").submit();

This approach proved successful for me personally

Answer №3

Utilize the powerful Jquery submit function.

For a helpful example, you can refer to this resource. Remember to include return:false; to prevent the form from being posted twice: once via jQuery and once from the button call within the form.

Another advantage is that in your MVC Action (in your controller), you can directly access your Model if you have one. By binding your model to text fields, you automatically receive an updated model without needing to parse the form collection.

This content contains code snippets from a personal project:

On a page object stored in the database.

When setting up the view, I opt for a strongly typed approach with the page object, leading to:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<LIB.Data.Page>" %>

I establish the connection between my model and textboxes:

<legend>Fields</legend>
<div class="editor-field">
    <%=Html.TextBoxFor(model => model.Title)%>
</div>

In the controller, the following actions are taken:

[HttpPost]
    [ValidateInput(false)]
    public ActionResult Create(Page model, FormCollection collection)
    {
        PageService.AddPage((string)Session["lang"], model);
        return RedirectToAction("Index", new { menuGuid = model.MenuGuid });
    }

The data inputs from the text fields are automatically bound to the model, which is then retrieved in the controller and stored.

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

Maintaining hot reload functionality by sharing components between two projects

We are currently working on developing 2 products utilizing Angular 2 (although the same issue may arise with React). Our goal is to find a way to share components between these two products. Initially, we considered breaking things up into npm modules as ...

What is the process for including parameters in a javascript/jquery function?

This unique script enables you to click on a specific element without any consequences, but as soon as you click anywhere else, it triggers a fade-out effect on something else. Within the following code snippet, you can interact with elements inside $(&apo ...

A guide on simulating an emit event while testing a Vue child component using Jest

During my testing of multiple child components, I have encountered a frustrating issue that seems to be poor practice. Each time I trigger an emit in a child component, it prompts me to import the parent component and subsequently set up all other child co ...

Ways to link the output from a dictionary to a class object using C# LINQ

Dictionary<Guid, string> userEventTriggers = RepositoryContainer.GBM.Flex.Admin_UserEventTriggers.AsQueryable() .Where(x => userEventTriggerIds.Contains(x.RecordID)).ToDictionary(x => x.RecordID, x => x.Name); Dict ...

"MongoDB Aggregating Data with Nested Lookup and Grouping

I have 3 collections named User, Dispensary, and City. My desired result structure is as follows: { _id: , email: , birthdate: , type: , dispensary: { _id: , schedule: , name: , address: , phone: , u ...

How to redirect in Next.js from uppercase to lowercase url

I'm trying to redirect visitors from /Contact to /contact. However, following the instructions in the documentation results in an endless loop of redirects. This is my attempted solution: // next.config.js async redirects() { return [ { ...

Notify the chat when a new record is added to the database

Alright, so here's the issue I'm facing. I created a chat application using PHP and MySQL, but I noticed that when I enter text, it doesn't update in the other window automatically. This led me to experiment with iframes, which I found much ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

How can the controller verify the presence of a particular column in an excel file during the data import process?

I have a controller function that successfully adds data into my database table from two different excel files with the same columns, except for one column. I need to implement a check in the controller while reading from the excel file to see if a specifi ...

What could be causing Node Pdfkit to sometimes generate a corrupted file within my code?

I've encountered an issue with my function that generates a PDF file and sends it via email using `pdfkit` and `nodemailer`. Occasionally, I receive a file that cannot be opened. I'm unsure why this happens sporadically while it works fine most o ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...

The use of Buffer() is no longer recommended due to concerns regarding both security vulnerabilities and

I'm encountering an issue while trying to run a Discord bot. The code I'm using involves Buffer and it keeps generating errors specifically with this code snippet: const app = express(); app.get("/", (req,res) => { if((new Buffer(req.quer ...

Utilizing jQuery to fetch the source value of an image when the closest radio button is selected

On my website, I have a collection of divs that display color swatches in thumbnail size images. What I want to achieve is updating the main product image when a user clicks on a radio button by fetching the source value of the image inside the label eleme ...

What is the best way to display an international phone number using Angular Material V6?

I've been working on a project that utilizes Angular Material V6. My goal is to display international phone numbers with flags in a Material component text box. After some research online, I came across an npm module that achieved this but it was tail ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Having trouble updating state in React after making a fetch request

I am encountering an issue with setting the current user after a successful login. Even though the login process is successful and the data is accurate, I am unable to set the state as the user data appears to be empty. UserContext.js import React, { useC ...

Calculate the total number of blank input boxes within a specific row of the table

What is the method to count the number of input boxes without a value in a table row using jquery? For instance: <table id="table1"> <tr class="data" id="row5"> <td><input type="text" value="20%" /></td> <td><input ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...