ajax updatetargetid with mvc partial views not rendering properly - c#

I have a view which contains a tab layout, each tab contains a form which I am submitting through ajax.beginform. If the modelstate is not valid I return the view which is where I cannot work out how to render the view properly. Currently when I submit one of the forms it renders the whole page again within my tab, which I don't want. I thought using ajax updatetargetid I could render the div that needs replacing, but as I said it renders the whole page within my tab.
View
#model Trakman_Portal_Administration.Models.VehList
#using Trakman_Portal_Administration.Models
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
#*<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>*#
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$("#tabs").tabs();
});
</script>
#{
ViewBag.Title = "Edit";
}
<div class="editBanner">
<div class="editor-label">
#* #{
string custCode = ViewBag.custCode;
}*#
#* <h2>#Html.Label(custCode, custCode )</h2>*#
<h2>#Html.Label(Model.Column_8, Model.Column_8 )</h2>
</div>
</div>
<h3 style="font-size:20px">Edit</h3>
<br />
#*
TAB 1 VEHICLE DATA SAVED TO VEHLIST
*#
<div id="tabs">
<ul>
<li>Vehicle</li>
<li>Page 1</li>
<li>Page 2</li>
</ul>
<div id="tabs-1">
#using (Ajax.BeginForm("Edit",null, new AjaxOptions
{
OnSuccess = "OnSuccessEditVehicle",
OnFailure = "OnFailureEditVehicle",
HttpMethod = "Post",
UpdateTargetId = "tabs-1"
}, new {id="EditVehicle"}))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>VehList</legend>
#Html.EditorForModel()
</fieldset>
<div style="position:relative;left:750px">
#Html.ActionLink("Back to List", "Index", new {custCode= ViewBag.custCode, conName = ViewBag.connectionName}) |
<input type="submit" value="Save" /></div>
}
#*
TAB 1 VEHICLE DATA SAVED TO VEHICLEDATA
*#
</div>
<div id="tabs-2">
#{
VehicleData vd = ((Trakman_Portal_Administration.Controllers.VehicleController)this.ViewContext.Controller).EditVDPartial(Model.Column_0);
}
#Html.Partial("EditVDPartial", vd)
#* <div style="position:relative;left:750px">
#Html.ActionLink("Back to List", "Index", new {custCode= ViewBag.custCode, conName = ViewBag.connectionName}) |
<input type="button" value="Save" onclick="submitVehicleDataForm()" /></div>*#
</div>
#*
TAB 3 VEHICLE DATA SAVED TO VEHICLE
*#
<div id="tabs-3">
#{
vehicle v = ((Trakman_Portal_Administration.Controllers.VehicleController)this.ViewContext.Controller).EditPartial(Model.Column_0);
}
#Html.Partial("EditPartial", v)
<div style="position:relative;left:750px">
#Html.ActionLink("Back to List", "Index", new {custCode= ViewBag.custCode, conName = ViewBag.connectionName}) |
<input type="submit" value="Save" /></div>
</div>
</div>
<br />
Controller
public ActionResult Edit(VehList vehlist)
{
tedb = new trakman_Entities(System.Web.HttpContext.Current.Session["connection"].ToString());
if (ModelState.IsValid)
{
vehlist.Column_8 = System.Web.HttpContext.Current.Session["staticCustCode"].ToString();
tedb.VehLists.Attach(vehlist);
tedb.ObjectStateManager.ChangeObjectState(vehlist, System.Data.EntityState.Modified);
tedb.SaveChanges();
var cust = tedb.customers.First(c => c.code == vehlist.Column_8);
//return RedirectToAction("Index", new { custCode = cust.code, conName = System.Web.HttpContext.Current.Session["connectionName"]});
}
ViewBag.Column_8 = new SelectList(tedb.customers, "code", "name", vehlist.Column_8);
return View(vehlist);
}

Related

ValidateInput Cross Site Scripting Prevention not working Asp.net MVC

Validate Input is not working.The form gets submitted and the success view is displayed even when the form is posted with html tags
<b> hello </b>
Why is the cross site scripting prevention not working? It should be enabled by default right?
Razor View
<h4 style="color:purple">
<b>ID:</b> #ViewBag.ID <br />
<b>Name:</b> #ViewBag.Name <br />
</h4>
<hr />
#using (Html.BeginForm("register", "Adder", FormMethod.Post))
{
<div class="form-group">
#Html.TextArea("comments");
<input type="submit" />
</div>
}
Controller Method
[HttpPost]
public string register(string val)
{
// quickdbEntities1 ent = new quickdbEntities1();
// Player p1 = ent.Players.FirstOrDefault(p => p.Name == "name");
//// ent.Players.Add(player);
//// int res = ent.SaveChanges();
// ViewBag.id = player.PlayerId;
// ViewBag.Name = p1.Name;
return ("success");
}
Update:
I have added DataAnnotation [Required] and now uses a form like this.Still the form submits
#model Vidly.Domain.Player
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts
{
#Scripts.Render("~/bundles/jqueryval" )
}
#using (Html.BeginForm("register", "Adder", FormMethod.Post))
{
<div class="form-group">
#Html.TextBoxFor(m => m.Name,new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Name)
<input type="submit" name="submit" />
</div>
}
It is because you are accepting the parameter as string and no validation script in view page (as of we can't see if the layout page has the scripts).

My question is that, i do SweetAlerts in my project but not working

i am trying to implement sweetalert in my project but i can not pick the problem where it exist, i do every thing properly but still not chase my goal in this scenario.
This is my View:
#model SSC_MVC.Models.Department
#{
// ViewBag.Title = "Create";
ViewBag.Title = Model.dpt_id == null ? "Create" : "Edit";
}
<script src="~/Scripts/jquery-1.12.4.min.js">
</script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>
<script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>
<link href="~/Content/sweetalert/sweet-alert.css" rel="stylesheet" />
<script type="text/javascript">
function validateData()
{
debugger;
if ($("#dpt_nam").val() == "")
{
swal("Please enter Name !");
return false;
} else
{
return true;
}
}
</script>
<h2>Create</h2>
#using (Html.BeginForm(FormMethod.Post) )
{
#Html.AntiForgeryToken()
<div class="col-md-12 form-horizontal">
<h4>Department</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.dpt_id)
<div class="form-group">
<div class="col-md-2">
#Html.Label("Name", htmlAttributes: new { #class = "control-label col-md-2 " })
</div>
<div class="col-md-8">
#Html.EditorFor(model => model.dpt_nam, new { htmlAttributes = new { #class = "form-control validateData" } })
#Html.ValidationMessageFor(model => model.dpt_nam, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#if (Model.dpt_id == null)
{
<input type="submit" onclick="Validate(this, event);" value="Create" class="btn btn-primary" />
}
else
{
<input type="submit" value="Edit" class="btn btn-success" />
}
</div>
</div>
#{
var message = TempData["AlertMessage"] ?? string.Empty;
}
<script type="text/javascript">
var message = '#message';
if(message)
alert(message);
</script>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#*#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}*#
There is my Model:
public string dpt_id { get; set; }
public string dpt_nam { get; set; }
public string dpt_typ { get; set; }
In view #dpt_nam is my model property, actually i want, when I click on submit button and if the user not complete the department Name the alert shows, like: Please enter Name !, so in that case i made a function named as ValidateData, u can see it in a view.
any one here who help me out?

Passing Value from URL using RenderPartial to another View

I have a View which uses #Html.RenderPartial for showing some data which is present on another View.
I want to send an ID present in the URL into the RenderPartial so that it can be utilized on the Other Page.
Following is my code of JobView.cshtml which uses #Html.RenderPartial:
#model NurseOneStop.SC.PostedJob
#{
ViewBag.Title = "JobView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="lstCard">
<div class="applied-view">
<p>
<b>Job Salary:</b> #Model.JobSalary
</p>
<p>
<b>Job Desc:</b> #Model.JobDesc
</p>
<p>
<b>Job Summary:</b> #Model.JobSummary
</p>
<p>
<b>Job Application Type:</b> #Model.JobApplicationType
</p>
<p>
<b>CategoryId:</b> #Model.Category
</p>
<p>
<b>Number Of Positions:</b> #Model.NumberOfPositions
</p>
<p>
<b>CreatedOn:</b> #Model.CreatedOn.ToString("MMM dd, yyyy")
</p>
<p>
<b>Skills:</b> #Model.SkillNames
</p>
<p>
<b>Status:</b> #if (Model.Status)
{
<span>Open</span>
}
else
{
<span>Class</span>
}
</p>
</div>
</div>
</div>
<hr />
<div class="row">
<div class="lstCard">
<h2>Applied Nurses List</h2>
#{
Html.RenderPartial("NurseListView", (List<NurseOneStop.SC.NurseProfile>)Model.AppliedNurses, new ViewDataDictionary { { "PostedJobId", Model.PostedJobId } });
}
</div>
</div>
<p class="back-tolist">
#Html.ActionLink("Back to List", "Index")
</p>
Below is my code for NurseListView.cshtml:
#model IEnumerable<NurseOneStop.SC.NurseProfile>
#foreach (var item in Model)
{
<div class="col-md-4 col-sm-6 col-xs-12">
<span><b style="color:#007976; font-weight:600;">#item.Title #item.FirstName #item.LastName</b></span><br />
<span><b>Profession:</b> #item.Profession</span><br />
<span><b>Mobile:</b> #item.PhoneNumber</span><br />
<span><b>Email:</b> #item.EmailId</span><br />
<span><b>Verified Email:</b> #(item.IsVerifiedEmail ? "Yes" : "No")</span><br />
<span><b>Verified Contact:</b> #(item.IsVerifiedContact ? "Yes" : "No")</span><br />
<span><b>Applied On:</b> #item.CreatedOn.ToString("dd-MMM-yyyy")</span><br />
<span><b>Skills:</b> #item.Skills</span><br />
<span><b>Address:</b> #item.AddressLine1, #item.AddressLine2 #item.ZipCode</span><br />
#*<span>#item.ProfileUrl</span>*#
<span>#item.CurrentPosition</span><br />
<span>#item.Summary</span><br />
<span>#item.PreferredJobLocation</span>
<p class="no-margin" style="text-align:right">
#Html.ActionLink("Download CV", "DownloadResume", "PostedJob", new { ResumeId = item.NurseResumeList[0].ResumeId , PostedJobId = item.PostedJobId}, new { #class = "btnViewJobDetails" })
View Profile
#Html.ActionLink("Message", "SendMessage", "Recruiter", new { NurseId = item.NurseId }, new { #class = "btnViewJobDetails" })
</p>
</div>
}
http://localhost:49509/PostedJob/JobView?PostedJobId=100162&returnUrl=%2FPostedJob%2FIndex
I want to pass PostedJobId which is shown in the URL on the click of Download CV option.
How to do that?
You have to use HttpContext.Current.Request.QueryString["PostedJobId"] in your partial view to access PostedJobId value from URL.
#Html.ActionLink("Download CV", "DownloadResume", "PostedJob", new { ResumeId = item.NurseResumeList[0].ResumeId , PostedJobId = Request.QueryString["PostedJobId"]}, new { #class = "btnViewJobDetails" })
You can add the following to your code:
#Html.ActionLink("Download CV", "DownloadResume", "PostedJob", new { ResumeId = item.NurseResumeList[0].ResumeId , PostedJobId = Request.QueryString["PostedJobId"]}, new { #class = "btnViewJobDetails" })

How to validate multiple Ajax loaded Partial Views?

I have a View, Contact, that loads n number of Caller partial views, m number of Child partial views, and one CallNote partial view all loaded via Ajax once the document is ready.
I'm able to add and remove Callers and Children too, so these numbers are not static.
Contact.cshtml, with some stuff removed:
#using Birth_To_Five.ViewModels
#model CallDetailViewModel
<div class="container">
<ul class="nav nav-tabs">
<li class="active">Call Detail</li>
#* Other tabs not shown here *#
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="tab-1">
#using (Html.BeginForm("SubmitCallDetailsAsync", "Home", FormMethod.Post))
{
<div class="well">
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CallThreadViewModel.Id)
<span style="color: red">
#Html.ValidationSummary()
</span>
#* Call Details *#
<div class="row">
<fieldset>
<legend>Call Details</legend>
</fieldset>
</div>
<div class="row">
<div class="form-group">
#Html.LabelFor(m => m.EnteredByEmail, new { #class = "control-label" })
#Html.ValidationMessageFor(m => m.EnteredByEmail, "", new { #class = "text-danger" })
#Html.TextBoxFor(m => m.EnteredByEmail, new { #class = "form-control", placeholder = "Who took the call" })
</div>
#* Other stuff *#
</div>
#* Caller Details *#
<div class="row">
<fieldset>
<legend>Callers</legend>
</fieldset>
</div>
#* Render each existing caller. Each caller gets their own well to create a visual separation between them. *#
#foreach (var callerViewModel in Model.CallerViewModels)
{
<div class="progress" id="callerLoadingBar-#callerViewModel.Id" data-callerid="#callerViewModel.Id" data-calldetailid="#Model.Id">
<div class="progress-bar progress-bar-striped active" role="progressbar" style="width: 100%">Loading Caller...</div>
</div>
}
<div id="newCaller"></div>
<div class="row">
#* Button to search for and add a caller *#
</div>
#* Children Details *#
<div class="row">
<fieldset>
<legend>Children</legend>
</fieldset>
</div>
#* Render each existing child. Each child gets their own well to create a visual separation between them. *#
#foreach (var childViewModel in Model.ChildViewModels)
{
<div class="progress" id="childLoadingBar-#childViewModel.Id" data-childid="#childViewModel.Id" data-calldetailid="#Model.Id">
<div class="progress-bar progress-bar-striped active" role="progressbar" style="width: 100%">Loading Child...</div>
</div>
}
<div id="newChild"></div>
<div class="row">
#* Button to search for and add a child *#
</div>
<div class="progress" id="callNoteLoadingBar">
<div class="progress-bar progress-bar-striped active" role="progressbar" style="width: 100%">Loading Call Note...</div>
</div>
</div>
<div class="row">
<div class="form-group">
<button class="btn btn-danger" type="reset">Reset</button>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
}
</div>
</div>
</div>
#section scripts
{
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#Scripts.Render("~/bundles/calldetailscripts")
}
Snippet from my JS script, callDetailFunctions:
$(document).ready(function () {
getCallNote('#callNoteLoadingBar', $('#Id').val());
getAllCallers();
getAllChildren();
});
// function getAllWhatever(){ Foreach loading bar, addCaller/Child/CallNotePartialView(..., ..., ..., etc.); }
function addWhateverPartialView(divToReplace, thingIWantId, callDetailId) {
$.ajax({
url: '/Home/GetWhateverPartialViewAsync',
data: {
thingIWantId,
callDetailId
},
type: "GET",
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Request: " + xmlHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
$(divToReplace).replaceWith(data);
}
});
}
Here in my HomeController I have the SubmitCallDetailsAsync method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SubmitCallDetailsAsync(CallDetailViewModel callDetailViewModel)
{
using (var unitOfWork = new UnitOfWork(ApplicationDbContext))
{
// Call Details
var callDetailServices = new CallDetailServices();
await callDetailServices.AddOrUpdateCallDetailFromCallDetailViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Callers
var callerServices = new CallerServices();
await callerServices.AddOrUpdateCallersFromCallDetailsViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Children
var childServices = new ChildServices();
await childServices.AddOrUpdateChildrenFromCallDetailsViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Call Note
var callNoteServices = new CallNoteServices();
await callNoteServices.AddOrUpdateCallNoteFromCallDetailsViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Check the model state (returns true if it's good, false otherwise.
// Also spits out some debug text for me to tell me what broke the Model)
if (!UtilityServices.CheckModelState(ModelState))
{
callDetailViewModel.DirectionChoices =
await unitOfWork.DirectionChoiceRepo.GetAllAsSelectListItemsAsNoTrackingAsync();
return View("Contact", callDetailViewModel);
}
await unitOfWork.CompleteAsync();
}
return RedirectToAction("Index");
}
The gist of what's happen is that I have a loading bar as a placeholder for each Caller, Child, and the Call Note and then when the document loads I go and get those on $(document).ready()
My problem is that when I submit Contact.cshtml and hit a model validation error I get sent back to my Contact page, which reloads all the Callers, Children, and the Call Note, thus losing all changes.
What should/can I do to handle this scenario?
With deloopkat's comment, I was able to get this working (for the most part)
I changed my Contact page to use Ajax.BeginForm() and added a partialCallDetail id to the section I want to replace with a Partial View result:
#using (Ajax.BeginForm("SubmitCallDetailsAsync", "Home", new AjaxOptions() {HttpMethod = "POST", UpdateTargetId = "partialCallDetail", OnSuccess = "onSuccess"})) #* <----------- Note the UpdateTargetId *#
{
<div class="well">
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CallThreadViewModel.Id)
<span style="color: red">
#Html.ValidationSummary()
</span>
#* Call Details *#
<div id="partialCallDetail"> #* <------------------ This whole div gets replaced by the Submit function when the Model Validation fails *#
#* All of the same stuff as before in my original post *#
</div>
</div>
<div class="row">
<div class="form-group">
<button class="btn btn-danger" type="reset">Reset</button>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
}
#section scripts
{
<script>
function onSuccess(data) {
///<summary>
/// When the Ajax form is submitted, this function gets called with the return data.
/// Determine if it contains a redirectUrl and go there if it does
///</summary>
if (data.redirectUrl !== undefined) {
window.location.replace(data.redirectUrl);
}
}
</script>
}
I created a separate Partial View, _PartialCallDetail, that renders each Caller, Child, and CallNotes PartailView on the spot rather than calling a function via Ajax on $(document).ready()
...
#* Render each existing caller. Each caller gets thier own well to create a visual seperation between them. *#
#foreach (var callerViewModel in Model.CallerViewModels)
{
Html.RenderPartial("_PartialCallerInfo", callerViewModel);
}
...etc.
I then changed my Submit function to this:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SubmitCallDetailsAsync(CallDetailViewModel callDetailViewModel)
{
using (var unitOfWork = new UnitOfWork(ApplicationDbContext))
{
// Call Details
var callDetailServices = new CallDetailServices();
await callDetailServices.AddOrUpdateCallDetailFromCallDetailViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Callers
var callerServices = new CallerServices();
await callerServices.AddOrUpdateCallersFromCallDetailsViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Children
var childServices = new ChildServices();
await childServices.AddOrUpdateChildrenFromCallDetailsViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Call Note
var callNoteServices = new CallNoteServices();
await callNoteServices.AddOrUpdateCallNoteFromCallDetailsViewModelAsync(callDetailViewModel, ModelState, unitOfWork);
// Check the model state
if (!UtilityServices.CheckModelState(ModelState))
{
// Setup all drop downs
callDetailViewModel.DirectionChoices =
await unitOfWork.DirectionChoiceRepo.GetAllAsSelectListItemsAsNoTrackingAsync();
foreach (var callerViewModel in callDetailViewModel.CallerViewModels)
{
await callerServices.SetupSelectListItemsAsync(callerViewModel, unitOfWork);
}
foreach (var childViewModel in callDetailViewModel.ChildViewModels)
{
childViewModel.SexChoices = await unitOfWork.SexChoiceRepo.GetAllAsSelectListItemsAsNoTrackingAsync();
}
// Return the ViewModel with Validation messages
if (Request.IsAjaxRequest()) return PartialView("_PartialCallDetail", callDetailViewModel);
return View("Contact", callDetailViewModel);
}
await unitOfWork.CompleteAsync();
}
return Json(new { redirectUrl = Url.Action("Index", "Home", null) });
}
Now when there is a Model Validation error, I send back my _PartialCallDetail view, which updates the Contact page with the existing data and activates the #Html.ValidationMessageFor(...)s
I think it's important to note that this isn't perfect in it's current state:
I now have two Views, Contact and _PartialCallDetail, that I need to update if I make a design change in the future.
The #Html.ValidationSummary() I have in my View is only for non-Ajax content, so the User's have to sift through the View to see what's wrong.
And a couple other specific-to-my-code issues too, but I'll leave those out.
But I feel pretty good that this is a step in the right direction

ASP.NET Return View("Index"); Return to same tab

I have a single asp.net page it contains a number of tabs and a datetime picker.
When the user selects a date from the datetime picker and clicks on the update button it does that it should do but it does not return the user to the same tab.
HTML Code
<ul class='tabs'>
<li><a href='#tab1'>Production</a></li>
<li><a href='#tab2'>Page2</a></li>
<li><a href='#tab4'>Page3</a></li>
<li><a href='#tab6'>Page4</a></li>
</ul>
<div id='tab1'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
<div id='tab2'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
<div id='tab3'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
<div id='tab4'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
C# code
I do what i need to do and return to the Index form is there any way to specify what tab to return too.
return View("Index");
How about using hidden field + jquery, like this:
Update your ViewModel and add an int property for example LastTabIndex, then Add a hidden field to your form:
#Html.HiddenFor(m=>m.LastTabIndex)
and then use jquery :
<script type="text/javascript">
$(function() {
$(".tabs").tabs({
create: function() {
var index = 0;
if (Modernizr.localstorage) {
if (localStorage.getItem("LastTabIndex") === null) {
localStorage.setItem("LastTabIndex", 0);
} else {
index = localStorage.getItem("LastTabIndex");
}
} else {
index = $('#LastTabIndex').val();
}
$(".tabs").tabs("option", "active", index);
},
activate: function() {
var sel = $('.tabs').tabs('option', 'active');
$("#LastTabIndex").val(sel);
if (Modernizr.localstorage) {
localStorage.setItem("LastTabIndex", sel);
}
}
});
});
</script>
EDIT: I've updated my code to use a hybrid solution (localstorage and if local storage is unsupported then use hidden field).
Hope this helps!
Regards,
Uros

Categories

Resources