Get button clicked ID in "OnSuccess" function after form submit - javascript

I am Using Ajax form in mvc3.
Below is code.
<% using (Ajax.BeginForm("Method", "Conroller", new AjaxOptions
{
UpdateTargetId = "PopupBody",
HttpMethod = "post",
OnSuccess = "OnSuccessContactInfoSave"
}, new { #id = "frmContactInfo" }))
{ %>
function OnSuccessContactInfoSave( data, textStatus ) {
alert( 'completed with success.' );
}
Now, i have 2 buttons on a page one is submit button and another is normal button.
Now, i want to know the clicked button in Onsuccess function .
How can i get it in "OnSuccessContactInfoSave" function?
Thanks in Advance
Edited :
This is My View
<% using (Ajax.BeginForm("SaveContactInfo", "ManageUser", new AjaxOptions
{
UpdateTargetId = "PopupBody",
HttpMethod = "Post"
}))
{ %> <div class="ciMain">
<input type="submit" id="btnSaveAndClose" name="btn" value="Save" />
<input type="submit" value="Save and continue to next step" name="btn" />
<input type="button" value="Cancel" />
</div>
<% } %>
This is Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveContactInfo(FormCollection userViewModel, ContactInfoViewModel model, string btn)
{
//string test = Request["btn"].ToString();
try
{
return View("ContactInfo", model);
}
catch (Exception)
{
return View("ContactInfo", model);
}
}

First you need to create a property with the name SubmissionType in the model class
ContactInfoViewModel like this:
public class ContactInfoViewModel
{
public string SubmissionType { get; set; }
//Your rest of properties
}
Now in your view pass this property name in your submit button something like this:
<input type="submit" name="SubmissionType" id="btnSumit" value="Submit"/>
<input type="submit" name="SubmissionType" id="btnOther" value="Other"/>
Remember these buttons must be under form tag and also dont forget to bind your model with the view something like this:
#model ClassNamespace.ContactInfoViewModel
now you have to restructure your action method like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveContactInfo(ContactInfoViewModel model)
{
if (model.SubmissionType == "Submit")
{
}
else
{
}
try
{
return View("ContactInfo", model);
}
catch (Exception)
{
return View("ContactInfo", model);
}
}
Now coming to your ajax form tag, you also have to pass Model here so that you can get the values of your model at the time of form submission. Do it like this:
#using (Ajax.BeginForm("SaveContactInfo", "ManageUser",Model, new AjaxOptions
{
UpdateTargetId = "PopupBody",
HttpMethod = "Post"
}))
As you can see in the above code I have also passed model as object routeValues.
Hope now this will solve your problem.

Related

Updating the View with Model changes via Ajax Post by calling a javascript function

I use an Ajax call to update my model value and then have that new value should be shown in the view. Here is my code . In this code I am calling a method GetText and updating model value. How can I show the new model value in the html. Please help
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>
You can use return Content() to return string to ajax function.
[HttpPost]
public IActionResult GetText(EmpModel model)
{
model.EmpClaim = "New Text" // This should be shown in view
return Content(model.EmpClaim);
}
Js:
<script>
function changeText()
{
var url = '#Url.Action("GetText", "EmpDoc")';
$.post(url, $('form').serialize(), function (view) {
$("#TxtClaim").val(view); // How can I update the TxtClim with model.EmpClaim "New Text"
});
}
</script>
Here is the result:
Note:
In your case, the model does not have a key field, so when you update the data, you cannot determine which piece of data to update. Further operations may require you to modify the model design.
You can refer to this.

Multiple submits in a MVC application via jQuery

I have 2 anchor links in my view, on which I am trying to hit the HTTP POST method on the controller. The POST method has a condition in which it checks value of a hidden field, and on the basis of the condition, it tries to redirect to different views.
Facing a problem that the value of the hidden field is being NULL everytime, irrespective of the fact that I am setting the value of the hidden field via jQuery.
Below is the code:
<form id="CreateForm" asp-action="CreateForm" method="post" role="form">
<a style="cursor:pointer" onclick="Submit();" id="finishCreateForm">Finish</a>
#Html.Partial("~/_Partial1.cshtml", Model.Contact)
</form>
#section Scripts {
<script>
function Submit() {
$("#CreateForm").submit();
$("#myHiddenField").val = "SubmitCreateForm";
}
</script>
}
<input type="hidden" name="nameHiddenField" id="myHiddenField"/>
In the partial _Partial.cshtml, we have another anchor link, as below:
#model Contact
<span>
<input asp-for="AddressLine1" value="#Model.AddressLine1" />
<span asp-validation-for="AddressLine1"></span>
<a id="find" value="findSubmit" onclick="Find();" style="cursor:pointer">Find</a>
</span>
<script>
function Find() {
$("#CreateForm").submit();
}
</script>
The controller code:
[Route("CreateForm")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateForm(InputViewModel inputVM)
{
if (ModelState.IsValid)
{
//Some business logic stuffs, code removed for brevity
if (inputVM.myHiddenField== "SubmitCreateForm")
{
return RedirectToAction("Test", "Home", new { area = "Shared" });
}
else
{
return RedirectToAction("Search", "MySearch", new { id= response.Id, type= response.Type, area = "Search" });
}
}
else
{
//Some more logic
}
}
I have also added myHiddenField in the model coming to the POST action method, as
public string myHiddenField{ get; set; }
I know I am missing a very basic stuff, please guide accordingly.
Thanks

How to refresh only one Html.ListBox in asp.net razor?

I tried to refresh only one Html.ListBox. But i don't know how to do this with ASP. Right now it will refresh the whole page.
Here is my source:
Controller
[HttpPost]
public ActionResult KenmerkSelectie(string Kenmerken1, string Buttontype, List<string> VarFromKenmerk1)
{
if (Buttontype == "submit")
{
//Write to a database and process stuff
return this.RedirectToAction("submitForm");
}else{
ViewBag.VarFromKenmerk1 = ...;
//TODO: Must refresh the ListBox: VarFromKenmerk1;
//AND AND NOT refresh whole page;
return View("index");
}
html view:
#using (Html.BeginForm("KenmerkSelectie", "KenmerkSelectie", FormMethod.Post, new { id = "kenmerk1" }))
{
#Html.DropDownList("Kenmerken1",
(SelectList)ViewBag.Kenmerk,
"-- Selecteer een kenmerk--", new
{
onchange = "refreshVarFromKenmerk1();"
})
#Html.ListBox("VarFromKenmerk1", (SelectList)ViewBag.var, new { #style = "width: 252px; height: 300px" })
<input type="submit" value="submit" id="btnNext" name="ButtonType" />
}
Javascript:
<script type="text/javascript">
function refreshVarFromKenmerk1() {
document.getElementById('kenmerk1').submit();
}
</script>
Is it possible to achieve this without Javascript? Or better how do I achieve this?
I think what you are looking for is Request.IsAjaxRequest() in your controller. You can fire an Ajax request like:
$('#kenmerk1').change(function () { $.get(); /* this won't work but shows the basics */ });
Then, you can return a JsonResult in the controller and refresh the list box.

Prevent from ajax call in MVC

Hi i am making my project in the asp.net,
basic expected behaviour -- fill form name , select master module(dropdown), select sub modules(dropdown), ajax passes id of submodule dropdown, create(submit).. it will submit all values,
now code is behaves---- fill form name, select master and submodule, while selecting submodule from second dropdown is calling the ajax call, and create action is called, so the form name and masterID(that is extracted from first dropdown) gone blank... so i need to prevent the ajax call to call the controller
Myform in razor view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FormName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FormName)
#Html.ValidationMessageFor(model => model.FormName)
</div>
<select id="State" name="state"></select><br />
<p>
<input id="sbmt" type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My ajax call
$('#State').change(function () {
var a = $('#State').val();
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
url: "/form/create",
type: "POST",
data: { __RequestVerificationToken: token, 'SubID': a }
});
});
My controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Form form, int SubID)
{
if (ModelState.IsValid)
{
form.CreatedBy = 1;
form.SubId = SubID;
form.CreatedDate = DateTime.Now;
form.ModifyBy = 1;
form.ModifyDate = DateTime.Now;
form.IsActive = true;
form.IsDeleted = false;
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MasterID = new SelectList(db.Departments, "MasterId", "ModuleName", form.MasterID);
return View(form);
}
From the comments, you want to be able to post back the value of the selected state when you submit the form. The best approach would be to use a view model that includes the property SubId and bind your dropdownlist to that property (the SubId parameter in you POST method is then not necessary.
#Html.DropDownListFor(m => m.SubId, ....)
The alternative is to rename the control to SubId so it matches the parameter in your POST method
<select name="SubId" ...>
and delete the unnecessary javascript function $('#State').change(function () {...
I guess the easiest way for you would be to use MVC's ajax helpers. Change your form like so:
#using (Ajax.BeginForm("Create", "Home", null, new AjaxOptions { OnSuccess = "OnSuccess" }))
{
...
And afterwards add a javascript handler for onsuccess
function OnSuccess(){
alert("success");
}
This is barely functional code just to get you started.
PS. Make sure you add a reference to ~/Scripts/jquery.unobtrusive-ajax.min.js

can we pass entire model to javascript asp.net mvc

I have a problem that on javascript call for the form submit , the model gets updated from controller ,but it is not updating in the view. I am thinking to update the model to new model values in javascript . so that the view shows the latest model values
can that be done?
thanks,
michael
Your question is extremely unclear and you provided no source code which makes things even more unclear. From the various comments you may have posted I assume that you are trying to update some model value inside the POST action without removing it from the model state and when the same view is rendered again the old values are displayed.
So I suppose you have a view model that looks something close to this:
public class MyViewModel
{
public HttpPostedFileBase File { get; set; }
public string SomeValue { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SomeValue = "initial value"
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// Notice how the SomeValue property is removed from the
// model state because we are updating its value and so that
// html helpers don't use the old value
ModelState.Remove("SomeValue");
model.SomeValue = "some new value";
return View(model);
}
}
and a view:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<div>
<%= Html.LabelFor(x => x.SomeValue) %>
<%= Html.EditorFor(x => x.SomeValue) %>
</div>
<div>
<label for="file">Attachment</label>
<input type="file" name="file" />
</div>
<input type="submit" value="OK" />
<% } %>

Categories

Resources