i have two views:
Index
Create
Contents of each view:
Index
'Create' link
display records from table in database.
Create
Create new record and save it and back to index view.
I want to display the Create view in the Index view when users click on 'Create' Link. What is the best way to do it?
You may use jQuery load() function. You need to change your Create View to PartalView.
Then on your Index View you need something like that:
Create
<div class="divForCreate"></div>
<script>
$('.Create').click(function() {
$('.divForCreate').Load('#Url.Action("Create", "Home", new {id = Model.id})')
});
</script>
Your demand can also be realized using $.ajax(), which is a little bit complex than simply using load(), but can easily applied when your data come from a different domain. For example,
<input type="submit" value="create" onclick="create();"/>
<div id="bottom_row"></div>
<script>
function create(){
//you can get your paramters like this.
var link_head = $("#link_head").val();
$.ajax({
type : "get",
async:false,
url : "http://yourIP:port/path to method.action?paramters,
dataType : "jsonp",
jsonp: "callbackparam",
jsonpCallback:"success_jsonpCallback",
success : function(json){
if(json.Status){
location.reload();
//your further action here
}else{
alert("Error");
}
},
error:function(){
alert('fail');
}
});
}
</script>
Related
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.
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.
I am using ASP.NET MVC 3 EF Code First with Razor + SQLserver and Want to implement Master Details scenario (like Order, Orderlines) with CRUD operations. I have come across some online examples like http://hasibulhaque.com/index.php/2011/master-detail-crud-operations-ef-asp-net-mvc-3/ but they heavily depends on JQuery or other complex implementations. Can somebody suggest me some step by step approach with a clean code?
there are good tutorials at the asp.net site.
and i recommend you switch to mvc4 learning.
here is a link:
http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
If you want scaffolding do it for you, unfortunately it's not possible and you can't do that simply. Besides, you must use jquery and ajax to implement what you want.
I think the best and simplest way for you is that you have a view for creating Form and at the bottom of it put a fieldset to assign FormFields to it.
For the fieldset, you should have two partial views: One for create and another for edit. The partial view for creating should be something like this:
#model myPrj.Models.Form_FormFieldInfo
#{
var index = Guid.NewGuid().ToString();
string ln = (string)ViewBag.ListName;
string hn = ln + ".Index";
}
<tr>
<td>
<input type="hidden" name="#hn" value="#index" />
#Html.LabelFor(model => model.FormFieldID)
</td>
<td>
#Html.DropDownList(ln + "[" + index + "].FormFieldID",
new SelectList(new myPrj.Models.DbContext().FormFields, "ID", "FieldName"))
</td>
<td>
<input type="button" onclick="$(this).parent().parent().remove();"
value="Remove" />
</td>
</tr>
By calling this partial view in the create place view ajaxly, you can render some elements for each tag. Each line of elements contains a label, a DropDownList containing tags, and a remove button to simply remove the created elements.
In the create place view, you have a bare table which will contain those elements you create through the partial view:
<fieldset>
<legend>Form and FormFields</legend>
#Html.ValidationMessageFor(model => model.FormFields)</label>
<table id="tblFields"></table>
<input type="button" id="btnAddTag" value="Add new Field"/>
<img id="imgSpinnerl" src="~/Images/indicator-blue.gif" style="display:none;" />
</fieldset>
and you have the following script to create a line of elements for each tag:
$(document).ready(function () {
$("#btnAddField").click(function () {
$.ajax({
url: "/Controller/GetFormFieldRow/FormFields",
type: 'GET', dataType: 'json',
success: function (data, textStatus, jqXHR) {
$("#tblFields").append(jqXHR.responseText);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#tblFields").append(jqXHR.responseText);
},
beforeSend: function () { $("#imgSpinnerl").show(); },
complete: function () { $("#imgSpinnerl").hide(); }
});
});
});
The action method GetFormFieldRow is like the following:
public PartialViewResult GetFormFieldRow(string id = "")
{
ViewBag.ListName = id;
return PartialView("_FormFieldPartial");
}
and your done for the create... The whole solution for your question has many codes for views, partial views, controllers, ajax calls and model binding. I tried to just show you the way because I really can't to post all of them in this answer.
Here is the full info and how-to.
Hope that this answer be useful and lead the way for you.
I have an asp.net view which has two partial views. One for edit information and other one for displaying list of changes that were made. When I hit the update button, the list is not updated. I used ajax.begin form. How can I do this?
Main view has like this:
<div class="accountdetails1">
#Html.Action("UpdateAccountDetails", new { dispute = dispute })
</div>
<div>
list of changes
#Html.Action("GetAccountAudit")
</div>
updateAccountDetails is like this in start:
#using (Ajax.BeginForm("UpdateAccountDetails", new AjaxOptions
{
LoadingElementId = "loading",
LoadingElementDuration = 2000,
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
}))
{
and functions are like this:
<script type="text/javascript">
function OnSuccess() {
var div = $('#dvMessage');
div.html('');
div.append('Account Information has been updated.');
}
function OnBegin() {
var div = $('#dvMessage');
div.html('');
}
</script>
to show success or failure of update Do I need to update change list in success method? Please suggest
#Ajax methods works in following way:
#Ajax.ActionLink - requests HTML from pointed action via AJAX and puts result in HTML element with id equals to UpdateTargetId value specified in AjaxOptions.
#Ajax.BeginForm - gets the all inputs and selects and other form elements inside using(Ajax.BeginForm()) { .. } and submits it to specified action (using AJAX) then puts response to HTML element with id specified in AjaxOptions.UpdateTargetId property.
So you need something like
<div id="myContainer" >
#using(Ajax.BeginForm("yourActionToProcessEdits", new AjaxOptions { UpdateTargetId = "myContainer" }))
{
.. Form for edit information
#Html.EditorFor(m => m.EditMe)
...
<input type="submit" value="Update" />
.. Display changes here
#Html.Raw(Model.MyChanges)
}
You need to request the GetAccountAudit action to return the list. The beginform is only requesting the UpdateAccountDetails action.
You could do a jquery ajax request in the onSuccess function to request the GetAccountAudit action and update the html.
Could the two actions be combined so that the list would be returned in the UpdateAccountDetails view?
I'm trying to incorporate jqueryUI's datepicker inside a partialview like this:
<% using (Ajax.BeginForm("/EditData",
new AjaxOptions { HttpMethod = "POST",
UpdateTargetId = "div1" }))
{%>
Date:
<%= Html.TextBox("date", String.Format("{0:g}", Model.date), new { id = "datePicker"})%>
<% } %>
<script type="text/javascript">
$(function() {
$("#datePicker").datepicker();
});
</script>
When I directly call the url to this partial view, so it renders only this view the datepicker works perfectly. (For the purpose of testing this I added the needed jquery and jqueryui script and css references directly to the partial view)
But if I use a Ajax.Actionlink to load this partial view inside a div (called div2, submitting the above form should update div1) like this:
<div id="div1">
<%= Ajax.ActionLink("Edit", "/EditData", new { id = Model.id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div2" } )%>
</div>
<div2>placeholder for the form</div>
The datepicker won't appear anymore.
My best guess is the javascript included in the loaded html doesn't get executed,
($(document).ready(function() {
$("#datepicker").datepicker();
}); doesnt work either
If that's the case how and where should I call the $("datepicker").datepicker(); ?
(putting it in the ajaxoptions of the ajax.actionlink as oncomplete = "$(function() {
$('#datepicker').datepicker();});" still doesnt work.
If that's not the case, then where's my problem?
The answer given by veggerby probably will be working in the given scenario, therefor i marked it as correct answer.
My problem here was that the javascript is in a portion of html being dynamicly loaded thrue ajax. Then the loaded javascript code wont be picked up by the javascript interpreter (or whatever im supposed to call the javascript handling on the clientside).
In my case veggerby's sollution wouldnt work either but that's because in my app i even loaded that piece of html+javascript thrue ajax. which results in the same problem.
i didnt feel like putting the javascript in the first normally loaded page, since it doesnt always load the same piece of app (thus possibly executing code when its not needed).
i resolved this by creating a sepperate .js script which is included in the site.master:
function rebindJQuery(data) {
jQuery('#div2').html(data.get_data());
jQuery('#datepicker').datepicker();
return false; //prevent original behavior, in this case folowing the link
}
which gets executed by
<%= Ajax.ActionLink("Edit", "/EditData", new { id = Model.id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div2" , oncomplete="rebinJQuery" } )%>
i have yet to find a way to get the UpdateTargetId into my rebindJQuery(data) function, so this can be more generic. Nontheless this solves my problem. (and a couple of compairable questions asked here on stackoverflow)
I don't know why that does not work, but you could skip using the Ajax.ActionLink and instead use JQuery on itself to do this task, i.e.:
<div id="div1">
<%= Html.ActionLink("Edit", "/EditData", new { id = Model.id } )%>
</div>
<div2>placeholder for the form</div>
<script type="text/javascript">
$(document).ready(function() {
$("#div1 a").click(function() {
$.get(
$(this).attr("href"),
null,
function (data) {
$("#div2").html(data);
$("#datepicker").datepicker();
});
return false; // to prevent link
});
});
</script>
jQuery live events might be useful.
http://docs.jquery.com/Events/live