asp.net mvc Ajax.BeginForm duplicating elements - javascript

I am using ajax to load data using partial view and at the same i have implemented search functionality. Its working fine but when i keep my search textbox empty and then hit search button then my layout gets duplicated.
here is my code
controller :
public async Task<ActionResult> Index(string search)
{
if (!Request.IsAjaxRequest())
return View(await _employeeRepository.GetAllEmployeesAsync());
if (string.IsNullOrEmpty(search))
return View(await _employeeRepository.GetAllEmployeesAsync());
return PartialView("_EmployeeList",(await _employeeRepository
.GetAllEmployeesAsync())
.Where(x =>x.EmployeeName.StartsWith(search,
StringComparison.OrdinalIgnoreCase)));
}
Index.cshtml
#model IEnumerable<MvcDemo.Models.Employee>
#using (Ajax.BeginForm("Index", "Employee", new AjaxOptions
{
OnFailure = "record not loaded",
HttpMethod = "GET",
UpdateTargetId = "employeeData",
InsertionMode = InsertionMode.Replace
}))
{
<input type="text" name="search"
class="form-control"
placeholder="search by name..."/>
<input type="submit" value="Search"/>
}
<div id="employeeData">
#Html.Partial("_EmployeeList", Model);
#* i have used render partial as well*#
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryajax")
}
BundleConfig:
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js"));
Layout.cshtml :
#Scripts.Render("~/bundles/jqueryajax")
Can anybody tell me where i am going wrong ? Keeping the input blank and clicking on search button duplicating the layout.
Take a look at my screenshot screen 1 screen 2 screen 3
Any help would be much appreciated.

If search text is null or empty, you are returning the index view, instead of this return partial view.
if (string.IsNullOrEmpty(search))
return PartialView("_EmployeeList", (await _employeeRepository.GetAllEmployeesAsync()));

Related

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

Ajax form: OnSuccess, load partial div

I have this Ajax Form
#using(Ajax.BeginForm("AddAttendeeManual", "Attendee", new AjaxOptions { HttpMethod = "POST", OnSuccess = "doneManualEmail" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
#Html.TextBoxFor(m => m.SelectedManualEmail.Email, new {#class = "form-control",PlaceHolder="Email"})
</div>
<input type="submit" id="btnManual"class="btn btn-default" value="Add>>" />
}
and a div, both are on same view
<div id="invitedPeoples" data-url="#Url.Action("InvitedAttendees", "Attendee", new { appointmentId = Model.AppointmentId })">
</div>
Everytime the form is submitted, I wanted to load the div that should have a partial view.
This is what I have done
function doneManualEmail(isRequestSucceded) {
$(#Html.IdFor(m=>m.SelectedManualEmail.Email)).val('');
var url = $("#invitedPeoples").data('url');
$.get(url, function (data) {
$('#invitedPeoples').html(data);
});
};
everytime the form is submitted, i get forwarded to InvitedAttendees method, but my partial view doesn't show up.
The first line of the jquery works fine but the part to load partial view doesn't work.
Any thing I'm missing?
Error in Console:

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

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.

Categories

Resources