MVC Form values not reset - c#

I have an issue where the hidden values in a form are not updating when the new ActionResult is returned.
For example, a user will check several records and click the Update Completion button. This makes an Ajax called to the UpdateCompleted action that sets a date for the checked records and once the Ajax call returns the form is submitted. After performing some logic in the form submit Action method, an updated model is returned with the IsChecked value set to false for all records in the model, but the form is retaining the previous checked value due to the generated id below having the same value.
Code
<td>
#Html.CheckBoxFor(model => Model.WorkOrderDetails[x].IsChecked)
#Html.HiddenFor(modelItem => Model.WorkOrderDetails[x].IsChecked)
#Html.HiddenFor(modelItem => Model.WorkOrderDetails[x].WorkOrderEntityId)
#Html.HiddenFor(model => model.WorkOrderDetails[x].WorkOrderId)
</td>
Rendered HTML
<td>
<input data-val="true" data-val-required="The IsChecked field is required." id="WorkOrderDetails_0__IsChecked" name="WorkOrderDetails[0].IsChecked" type="checkbox" value="true"><input name="WorkOrderDetails[0].IsChecked" type="hidden" value="false">
<input id="WorkOrderDetails_0__IsChecked" name="WorkOrderDetails[0].IsChecked" type="hidden" value="False">
<input id="WorkOrderDetails_0__WorkOrderEntityId" name="WorkOrderDetails[0].WorkOrderEntityId" type="hidden" value="ODU=">
<input id="WorkOrderDetails_0__WorkOrderId" name="WorkOrderDetails[0].WorkOrderId" type="hidden" value="NjQ4OTU3">
</td>
Submit Code
#using(#Html.BeginForm("Index", "WorkOrderMaster", FormMethod.Post, new { id = "workOrderMasterForm" }))
{
<div>
<div class="project-buttons">
<div class="btn-group">
<input id="submitCompletion" class="btn btn-success" value="Update Completion" data-submit-url='#Url.Action("UpdateCompleted", "WorkOrderMaster")' />
</div>
</div>
$(function () {
$('#submitCompletion').click(function () {
$.ajax({
type: 'POST',
url: $(this).data('submit-url'),
data: $('#workOrderMasterForm').serialize(),
success: function (data) {
$('#workOrderMasterForm').submit();
}
});
});
});
I would expect the new values from the model to be used but this is not occurring.
Is it recommended to code the input values manually in this situation in order to avoid the following format?
ClassName_Index_PropertyName
Thanks in advance for the time you took to look at this question.

Based on the provided code, you are performing an AJAX call to the server but expects the values to be cleaned up after the operation is finished.
It will not work since you are not refreshing the page. To clean up the form values without refreshing the page you need to do a small change in your code:
$(function () {
$('#submitCompletion').click(function () {
$.ajax({
type: 'POST',
url: $(this).data('submit-url'),
data: $('#workOrderMasterForm').serialize(),
success: function (data) {
$('#workOrderMasterForm').reset();
}
});
});
});
The change is in the success promise where "$('#workOrderMasterForm').sugmit();" changed to "$('#workOrderMasterForm').reset();".

In an effort to keep moving on this. I moved the form to a partial view, and added a div to load the partial view into. Anytime an event fires on the page thru many filters or the users submitting checked records the div is cleared and reloaded. This solved my issue.

Related

Change submit button value on click with AJAX

So I have a like button in my index view which looks like this. It calls the function "PostLike" which increases the number of likes by inserting a new row in my "like" table.
<form asp-action="PostLike" asp-route-id="#item.Id">
<input id="btn" type="submit" value="Like" class="btn btn-primary">
</form>
What I want to do is to change the value of the button from like to unlike when it's clicked, without refreshing the page and keeping the value after refreshing the app. Any ideas? I know I have to use some AJAX function for this to work, but I don't know how it should be implemented.
you can make an ajax call to check the success or error request status then change the value on the success method
ArticleLikeObj is the object to be sent to the controller to save like article action and it’s a view model class containing properties like ArticleId and current logged user
ajax call
<input id="#item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">
<input id="#item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">
<input id="#item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">
function Submit_clicked(clicked_id)
{
let ArticleLikeObj = {ArticleId:clicked_id, UserName:"Doe"};
SendRequest(ArticleLikeObj);
}
function SendRequest(ArticleLikeObj) {
$.ajax({
type: "POST",
url: '#Url.Action("action name","controller name")',
data: ArticleLikeObj,
contentType: 'application/x-www-form-urlencoded',
dataType: "json",
success: function (response) {
document.getElementById("Submit").value = "Liked";
},
error: function () {
alert("Error!");
}
});
}

How do I submit a form, but my text boxes preserve their values in asp.net Razor pages

I have a html form in which I write in a text box and submit when press a button and it saves in db but I want the page not to refresh and continue with the values ​​in the text box
I have see people talking about ajax but I have never worked with ajax
<div class="row" style="float:left; margin: 2px ">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-3">
<div class="form-group">
<label>Pressão Injeção:</label>
<input id="id3" type="text" name="Pressão_de_Injeção" /> <br />
</div>
</div>
Here is a quick example of an AJAX call which will POST data to an controller:
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log('success');
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Note, that you can also pass objects to the controller by supplying them as an variable within the data object:
var menuId = $("ul.nav").first().attr("id");
var obj = {
id: menuId,
text: "Foo"
};
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {name: "Jim", object: Obj},
dataType: "html"
});
(Code adapted from an answer by apis17.)
An introduction to AJAX, can be found here:
https://www.w3schools.com/js/js_ajax_intro.asp
The only other method of performing what you required (without using AJAX) is to use a form submit and pass the data back to the HTML form once complete. You would then need to re-populate the fields (however, this will cause additional work on both submitting and re-populating, if (and/or when) new fields are adding if the future).
You will have to take the ajax approach.
But if you don't want to do that, you can always post to the controller and return the model to the view. It will have the text you entered into the textbox.eg.
public IActionResult MyView()
{
return View();
}
[HttpPost]
public IActionResult MyView(MyModel model)
{
return View(model);
}
Hope this helps as an alternative.

Weird double post call in sitefinity

I have a very weird problem. Let's say I have two same forms/widgets on the same page , this is the code for the form:
<form>
<input class="form-group" type="text" title="FirstName" name="FirstName" id="FirstName" /><br />
<input class="form-group" type="text" title="LastName" name="LastName" id="LastName" /><br />
<input class="form-group" type="tel" title="PhoneNumber" name="PhoneNumber" id="PhoneNumber" /><br />
#Html.DropDownListFor(m => m.HearingID, Model.Hierings, new { #id = "HearingID", #class = "form-group" })<br />
#Html.DropDownListFor(m => m.ConnectTypeID, Model.ConnectTypes, new { #id = "ConnectTypeID", #class = "form-group" })<br />
<input type="button" value="Save" id="#buttonid" />
</form>
And the following js sends an ajax request.
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function (e) {
debugger;
e.preventDefault();
var form = $("form");
$.ajax({
type: "POST",
url: jQuery(location).attr('pathname') + '/Save/',
data: form.serialize(),
error: function (xhr, status, error) {
alert("Error");
},
success: function (e) {
}
});
});
return false;
});
</script>
By the laws of logic it should send the post request one time, but for some weird reason the number of calls correlates with the number of forms on the page. So if I have two forms - it sends the request two times. I tried everything, even giving the form a unique id, and yet still - two requests. The JS isn't working two times, the JS works one time but it still sends the request two times, and I can't figure out why.
I think you should give your form a unique ID which is generated on the server. In this way, when you drag your widget twice on the page, it will be rendered with different IDs, and moreover the jQuery selector will look for the form with the right ID. Following is a sample code of how I managed to get only one submit when I drag the widget two times on the page:
#{
// generate ID on the server
string formId = System.Guid.NewGuid().ToString();
}
<form id="#formId">
...
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#' + '#formId').submit(function (e) {
// code here
});
});
</script>

ASP.NET MVC: Put searching attributes into url (not query string)

have implemented filtering on my ASP.NET MVC 5 app.
My searchbox consists of a few Dropdownlists with predefined values. When the Dropdownlist value changes, the form is submitted and I see all available tickets for a specific method.
After the form submits the page reloads and I see the url like mysite.com/?Method=car. But I would like to get rid of the query string and put car directly into the url, i.e.
mysite.com/method/car or mysite.com/method/plain etc
Is it possible?
Search box
#using (Html.BeginForm("Search", "Transfer", FormMethod.Get))
{
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Method, Model.Methods, new { #class = "query"})
</div>
</div>
</div>
<input type="submit" class="hidden" />
}
My action method
[Route("~/transfer/{method?}")]
public async Task<ActionResult> List(string method)
{
//filter and displaying
return View(viewModel);
}
By default Html.BeginForm with FormMethod.Get will serialize all the form values into query string. So if you want friendly URLs you will have to write some JavaScript (jQuery in this example).
First of all you can remove the form
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Method, Model.Methods, new { #class = "query"})
</div>
</div>
</div>
<button type="button" id="submitMethodBtn">Submit</button>
<script>
var baseUrl = '#Url.Action("Search", "Transfer")/'
$('#submitMethodBtn').click(function(){
var url = baseUrl + $(#'#Html.IdFor(m=>m.Method)').val();
window.location.href = url;
})
</script>
Some issues/clarifications:
1if you enter mysite.com/method/car (assuming that issue #2 is resolved )in browser it will take you to a correct action so your issue is basically generating friendly Url in the view.
2 In the provided code example i used an inline script. You can extract it to a separate static file but you will have to hard-code the url and the html id for Method property.
3 Your action method gets int as parameter so how do you expect it to work with mysite.com/method/car (car is a string) ?
You can call an ajax method on page which will avoid query string and when controller redirects to ActionResult then again you can call ajax method on redirected page. By this way you can avoid query string in MVC.
Take below code as example.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Transfer/search",
data: "{ID:1}",
dataType: "json",
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Make return type as JsonResult of controller method.

issue calling a c# function from jquery

I am attempting to call a function through a view using jquery.. originally i was using razor's #html.BeignForm but for the web it needs to be converted to jquery
i don't know if i'm on the right path, however this is what i have in razor that's currently working.
#foreach(var up in Model)
{
#up._id
using (#Html.BeginForm("DQPost", "Disqus", new { ID = up._id }, FormMethod.Post))
{
<h7>The thread ID</h7>
<input type="text" name="ThreadID" /><br />
<h7>The message </h7>
<input type="text" name="Message" /><br />
<input type="submit" value="Post Comment"/>
}
}
what i'm trying to do is change the submit to button that then fires off the jquery. and this is the jquery i currently have written out.
<script type="text/javascript">
$(document).ready(function () {
$('#post').click(function () {
var dataToSend = { ID: ID, MethodName: 'DQPost', Message: message };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
});
});
</script>
any help would be greatly appreciated.
You are wrong here,$('#post').
$('#post').click(function () {
Post is not an identifier., so, you could declare your own. You could try something like
<input type="submit" id="submitButton" value="Post Comment"/>
Then,
$('#submitButton').click(function () {
will work fine.
Looks like you want to intercept the form submission so you can handle submit yourself with AJAX. If I'm reading that right, instead of attaching to the button's event, attach to the form's event:
$("#my-form-id").submit(function() {
// do my AJAX stuff
return false; // this will prevent the form from being submitted like normal
});

Categories

Resources