How to switch between view and edit views - asp.net-mvc

I have action method like this:
[ChildActionOnly]
public ActionResult NewUserLanguage()
{
...
return View(model);
}
This view have one simple form on it and a list of partial views:
<ul id="userLanguagesListBox">
#foreach (var l in Model.UserLanguages)
{
<li>
#{Html.RenderPartial("UserLanguageBox", l);}
</li>
}
...
This partial view looks like this:
...
#using (Html.BeginForm("EditUserLanguage", "UserLanguage", FormMethod.Post, new { id = "editUserLanagegeForm" }))
{
<ul>
<li><h3>#Model.Language.Name</h3></li>
<li>#Model.LanguageLevel.Name</li>
<li>
#Html.HiddenFor(x=>x.UserLanguageId)
<button class="editButton">Edit</button>
</li>
</ul>
}
What I am trying to do is when user click on edit button in any of the partials I want to switch it with another view EditUserLanguage.
I have tried something like this:
$(function () {
$('#editUserLanagegeForm').submit(function (e) {
alert('ss');
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$("#" + e.target).closest("div").append(result);
}
});
return false;
});
});
But this function is never called by any of edit buttons.

"The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus."
-From http://api.jquery.com/submit/
What this means to you is that you need your button to have a type of submit for the submit event to trigger, but I don't think that's the one you're thinking of. Try using .click() instead.

Related

Second time partialview not loading to div via from .ajax() in MVC4

I have issue loading partialview to div second time. I have checked previous posts in SO but non of them really helped me. So I am posting my issue here.
index.cshtml
<div id="DivEmailContainer" style="display:block" class="row">
</div>
_EditEmail.cshtml
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-2 ">
<input type="submit" value="Save" class="btn btn-success width100per" />
</div>
script type="text/javascript">
$(function () {
$("#frmEmail").validate({
rules: {
...
submitHandler: function (form) {
$.ajax({
url: 'PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
alert("In success");
$('#DivEmailContainer').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
complete: function (xhr, textStatus) {
alert(xhr.responseText);
alert(textStatus);
}
});
}
});
controller
public PartialViewResult PostEditEmail(string actiontype, FormCollection col)
{
var communicationLocation = string.Empty;
....
return PartialView("_EditEmail", memberemail);
}
First time partialview loading into DivEmailContainer to error. If submit again partialview loading full post back. not even it is calling submitHandler.
Only thing I observed is 1st time submit <form post was /ContactInformation/GetEditEmailbut when I submit second time <form post was /ContactInformation/PostEditEmail.
What could be wrong?
update
second time Forloop scriptblock loading. May be it is issue with Forloop?
#using (Html.BeginScriptContext())
{
Html.AddScriptBlock(
update
issue with forloop htmlhelper, not with ajax. secondtime script is not loading. #Russ Cam can help on this.
from my experience putting script in a partial leads to very inconsistent results. expecially with the script being inserted into the middle of the page. I would highly recommend that you pull your script from the partial and put it on the main page. Since the partial is loaded after the page load you will need to tie the script to the partial one of 2 ways.
1. tie the events to the document
$(document).on('click', '.targetClass', function(){
//do stuff
});
for example to put an id on your input and change it to a button
<input type="button" value="Save" id="btnSave" class="btn btn-success width100per" />
your click event would then be
$(document).on('click', '#btnSave', function(){
//your ajax call here
});
being tied to the document this click event would fire even though the input is inserted into the document after load
put the script in a function that is called after the partial is loaded
change your
$(function () {
to
function partialScript(){
and call this function after the partial is loaded
$('#DivEmailContainer').html(result);
partialScript();
Try to load partial view like this
$("#DivEmailContainer").load('#Url.Action('ActionName', 'ControllerName')', function () {
//Perform some operation if you want after load.
});

Parameter passed from view to controller not working

I have a very simple view and can't figure out why my textbox value is not passing to my controller. Will the actionlink work for providing the controller the parameter?
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("LookupEmployee", "Home")) {
<div class="jumbotron">
<h2>Personnel System</h2><br />
<p>ID: <input type="text" id=employeeID name="employeeID" /></p>
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null, new { #class = "btn btn-primary btn-large" })
</div>
}
<div class="row">
</div>
My HomeController takes the parameter and fills the dataset. I have hard coded a value and verified that this code works:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LeaveBalance(string employeeID)
{
//ViewBag.Message = "Your application description page.";
if (!String.IsNullOrEmpty(employeeID))
{
DataSet gotData;
LeaveRequestWCF myDataModel = new LeaveRequestWCF();
gotData = myDataModel.GetTheData(Convert.ToInt32(employeeID));
myDataModel.theModelSet = gotData;
return View(myDataModel);
}
return View();
}
}
Any advice? As you can tell, I'm new with MVC and trying to drift away from web forms.
OPTION 1:
You are using Html.ActionLink to post a form, which cannot be done because Html.ActionLinks are rendered as Anchor tags. Anchor tags make GET Requests unless we explicitly handle their JQuery click event. Use a Submit button to post a form for an appropriate controller action. So instead of -
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null,
new { #class = "btn btn-primary btn-large" })
go for -
<input type="submit" class="SomeClass" value="Submit" />
OPTION 2:
You can also use AJAX POST using JQuery click event for anchor tag to post the form and once you get the result, you can make a client side redirection.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#solTitle a").click(function() {
var data = {
"Id": $("#TextId").val()
};
$.ajax({
type: "POST",
url: "http://localhost:23133/api/values",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
// handle redirection here
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
ActionLink creates a simple <a href /> on the page, that will send a get request to the server.
You need a submit button instead, so your form gets posted with its form inputs. Use:
<button type="submit">Your Leave Balance</button>

two submit buttons on a form

lets say I have a set of establishments, each establishments know who his father is and a establishment can have many childs. now I created a set of cascading dropdowns for this problem so on the first whe find the ones that have no father ( tier 0 if you might), once the user selects an item the list on the second list its children are loaded ( if it has any children) and so on until tier 3, heres my code:
Index.cshtml:
#model WebUI.Controllers.IndexViewModel
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#Html.Partial("ParentEstablishments",Model)
<div id="FirstHeritage">#Html.Partial("FirstHeritageChildren",Model)</div>
<div id="SecondHeritage">#Html.Partial("SecondHeritageChildren",Model)</div>
Each partial view has an ajax form like the following:
#model WebUI.Controllers.IndexViewModel
#using (Ajax.BeginForm("SelectParent","Ticket",new AjaxOptions{UpdateTargetId="FirstHeritage"}))
{
<fieldset>
<legend>Entidad departamental</legend>
#Html.DropDownListFor(
m => m.SelectedParentId ,
new SelectList( Model.AvailableParents , "EstablishmentId" , "Name" ) ,
"[Por favor seleccione una entidad departamental]"
)
<input type="submit" value="Select" />
</fieldset>
}
so what i want to create is a submit button that lets the user tell me hes selected the entity he needs and to call a method on my controller where i check every id for a value, i tried to put the partial views inside a form but every submit button of the ajax forms calls the method of the form i create, how can i make a button without interfering with the ajax forms?
Modify the Button like below.
<input type="button" value="Select" class="btnSubmit" />
Mofify the Form Tag as mentioned below
#using (Ajax.BeginForm("SelectParent","Ticket", FormMethod.Post,
new { id = "myForm" }))
{
}
Modify the Div as mentioned below. Add an attribute which will have value corresponding to it's Controller's Action method.
<div id="FirstHeritage" attr-Url="#Url.Action("ActionName", "ControllerName",
new { area = "AreaName" })"></div>
Now in Jquery. Follow below steps.
Load Partial View
Fetch the Div Attribute Value
Use On for the Button event.
Ajax Request
JQuery
$(document).ready(function () {
var FirstHeritage = $('#FirstHeritage');
var url = FirstHeritage.attr('attr-Url');
FirstHeritage.load(url, function () {
var $form = $('#myForm');
$.validator.unobtrusive.parse($form);
$(document).on('click', '.btnSubmit', function () {
if ($form.valid()) {
$.ajax({
url: Url,
async: true,
type: 'POST',
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
$form.html(data);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
}
});
}
});
});
});
Hope this will help you.
You can't, essentially. The script that makes the AJAX form an AJAX form binds to the submit event, so any submit will be caught.
Remember all the HTML helpers and controls in ASP.NET are there to cover common scenarios and make your life easier when you're actually in a common scenario. The more "custom" your code gets (such as a second submit button that will do a regular POST instead of an AJAX POST), the more work you need to do (and the less you should be using the builtin helpers and controls).
Just create a regular form (Html.BeginForm), add your two submit buttons, and then attach a click event on the AJAX version, and then send the POST as AJAX yourself.

How to make ajax postback in form with list of check boxes

I dynamically draw checkboxes in my form:
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id="itemsList"}))
{
foreach (var lt in Model.MyList)
{
<li>
<label id="label">
<input value="#lt.itemId" type="checkbox" />
#lt.Title</label>
</li>
}
}
JQuery function:
$(document).ready(function () {
$('#itemsList').ajaxForm({
success: Saved,
error: HandleError
});
});
...
But my action is not fired. Am I doing something wrong here? I am expecting that when I check checkbox make server call.
I am expecting that when I check checkbox make server call.
You should not expect that unless you've written handler for checkbox change
$(document).ready(function () {
$('#itemsList').ajaxForm({
success: Saved,
error: HandleError
});
$(':checkbox').change(function(){
$('#itemsList').submit();
});
});
ajaxForm will intercept submissions and send them via ajax. But you need to trigger a submit for the ajax call to kick in.
Try adding:
$('input[#type="checkbox"]').click(function(){ $('#itemsList').submit(); }
You may want to refine the checkbox selector to something more specific...

Update viewdata on button clicks

<div id="newApplication" class="invisible">
<form id="frmnewApplication" action="">
<fieldset>
<ul class="formone">
<li>
<label class="labelone">
Name:</label>
<%-- <input type="text" id="ApplicationName" class="inputtext validate[required]" />--%>
<%= Html.DropDownList("ApplicationName", ViewData["AppList"] as IEnumerable<SelectListItem>)%>
</li>
This is my div. I am fetching the values from viewdata["AppList"]. My dropdown is fetching the values from ViewData in pageload only even though I am updating my viewdata in other controller methods it is not updating the viewdata. Plz help.
This is the jquery method
function updateDropdown() {
$("#ApplicationName").html("");
$.ajax({
type: "POST",
url: "/Shielding/AjaxGetDdlList",
dataType: "json",
success: function (data) {
if (data == null) {
alert("Something went wrong. Please try again;");
}
else {
for (group in data) {
var newOption = $("<option></option>").attr("value", data[group].ShieldFirewallApplicationId).html(data[group].ShieldFirewallApplicationName);
alert(data[group].ShieldFirewallApplicationName);
$("#ApplicationName").append(newOption);
}
}
}
});
}
This is the controller method:
public ActionResult AjaxGetDdlList()
{
return Json(ShieldingRep.GetAllApplications());
}
You may need to use tempdata. try to use viewmodels approach you may get help from this link
Viewdata isn't persisted between calls. The problem will be found in your controller.

Resources