Partial view not rendering MVC razor - ajax

It's my first time using partial views and I am unable to get the actual partialview. The ajax function gets called, the controller gets hit, and an alert in the ajax call shows me that the partialview is there. But, with errors written to the console (or alert) my div remains just as empty.
My application is an MVC4 app, but I am pretty sure I've just done a silly mistake somewhere and its not MVC's fault :)
AFter a few hours of googling, I would really be happy anybody can help me get this working, and all tips/comments on code/ajax i greatly appreciated!
public PartialViewResult Groups()
{
var person = _userRepository.GetCurrentUser();
var connections = (from c in person.Person1 select c).ToList();
var groups = _context.Groups.Where(g => g.GroupId == 1);
var all = new GroupViewModel()
{
Connections = connections,
GroupDetailses = (from g in groups
select
new GroupDetails
{
Name = g.Name,
StartDate = g.StartDate,
StartedById = g.StartedById,
})
};
return PartialView("Groups",all);
}
My PartialView
#model Mvc4m.Models.GroupViewModel
<h2>Groups</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<h3>Create new Group</h3>
<div class="ui-widget">
<label for="group">Groupname: </label>
<input id="group" />
<button onclick="addGroup()">Add</button>
</div>
#foreach (var item in Model.GroupDetailses)
{
#Html.LabelFor(model => item.Name)<text> : </text>
#Html.DisplayFor(model => item.Name)
}
<script>
function addGroup() {
$.get(
"/Profile/AddGroup",
{
Name: $("#group").val()
});
location.reload();
};
</script>
My Ajax call on Profile/Index
#model Mvc4m.Models.ProfileView
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="test" style="background-color:Aqua; width:200px; height:100px"></div>
<button onclick="load()"></button>
<script type="text/javascript">
function load() {
$.ajax({
type: "GET",
url: '/Profile/Groups',
dataType: 'html',
success: function (response) {
$('#test').html(response);
alert(response);
},
error: function (xhr, status, error) {
alert(status + " : " + error);
}
});
}
</script>

Turns out the code works, a restart of visual studio did the trick! How I hate VS sometimes...

Related

How to get input data from MVC ViewModel into ajax post

I am fetching data from a SQL database table into an ASP.NET MVC Razor view but I have troubles getting changed input data into an Ajax post such as:
#model MyViewModel
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
var postData = #Html.Raw(Json.Encode(#Model));
//alert(postData.Test);
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}
When I load the view everything is displayed correctly. The controller action is triggered correctly and the Id (which can not be altered) is passed properly too. However when input fields are changed not the changed values get passed to the controller but the original values that were fetched into the view.
The serialization seems to work, since the alert (postData.Test) returns a value - but always the unchanged one.
Any help would be appreciated.
var postData = #Html.Raw(Json.Encode(#Model));
This line is the culprit. When Razor renders the script, it will assign the original/unchanged model to your postData variable.
If you use "Inspect Element" or dev tools to check the value of postData, you'll see that the values won't change because they're statically assigned.
You need to check for the new values every time you click the button by using
var postData = $("form").serialize();
And be sure to wrap your input fields inside a form tag. See code below:
<form>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
</form>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
// use form.serialize or use the id/class of your form
var postData = $("form").serialize();
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}

How to call simple ajax program in asp.net mvc

I start learning Ajax in asp.net MVC 4. I want to create a very simple program based on the following scenario.
I want two textboxes on a form (FirstName, LastName) and a button, Whenever i write something in these textboxes, these values should assign to two labels (lblFristName, lblLastName) by using Ajax. So that page will not refresh.
How can i achieve the above functionality?. Please provide clear/simple code examples and no other site links, Thanks.
Following is the code that iam trying for:-
#model MvcAppLearn.Models.Student
#{
ViewBag.Title = "AjaxCall";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AjaxCall</h2>
#using (Html.BeginForm("AjaxCall", "Ajax", FormMethod.Post, new { id = "my-form" }))
{
#:FirstName #Html.EditorFor(x => x.FirstName);
#:FirstName #Html.EditorFor(x => x.LastName);
<input type="submit" value="Submit" />
}
<br />
<div id ="result">
</div>
#section scripts{
<script type="text/javascript">
$(function () {
$("#my-form").on("Submit", function (e) {
//e.preventDefault();
debugger
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
succes: function (data) {
$("#result").html(data);
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>
}
Partial View
#model MvcAppLearn.Models.Student
#{
ViewBag.Title = "AjaxCall";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ajax Partial View</h2>
<label>#Html.DisplayFor(item => item.FirstName)</label><br />
#Html.Label(Model.LastName)
#* #Html.EditorFor(x => x.FirstName)<br />
#Html.EditorFor(x => x.LastName)*#
Controller
public ActionResult AjaxCall()
{
return View();
}
[HttpPost]
public virtual ActionResult AjaxCall(Student model)
{
return PartialView("ajax_partial" , model);
}
So above code take me to the partial view, but i want to live on that page where my textboxes are placed and at the same page i want to display these labels. Please correct if there is any mistake, thanks
If this is something your view looks like,
#Html.TextBoxFor(r => r.textbox1, new { id = "textbox1"})
<label id="label1"></label>
You can achieve this using simple jquery change/keyup event
$('#textbox1').bind("change keyup", function() {
$('#label1').val($('#textbox1').val())
});
I have done it, Problem was i write "s" as capital in 'submit' and missed 's' in last at ":success" function. Following is the correct code.
<script type="text/javascript">
$(function () {
$("#my-form").on("submit", function (e) {
e.preventDefault();
//debugger
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$("#result").html(data);
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>

Open Telerik Window

I hope you can assist me with one dillema. I´m going to write a bunch of code before I ask my question below :)
When something is clicked on my page:
<input type='button' value='1' name='derp1' onclick='OpenTelerikWindow(1)' />
<br/>
<input type='button' value='2' name='derp2' onclick='OpenTelerikWindow(2)' />
I open Telerik Window with Jquery:
function OpenTelerikWindow(arg) {
var url = '/Controller/Derp/';
$.ajax({
type: "GET",
url: url,
dataType: "html",
data: { id: arg }
success: function (data) {
$('#PaymentWindow').data("tWindow").content(data);
$('#PaymentWindow').data("tWindow").center().open().refresh();
}
});
}
My Controller ActionResult:
public ActionResult Derp(int id)
{
SomeModel someModel = _GetModel(id);
return PartialView("Derp", someModel)
}
And then the content of my Telerik Window goes something like this:
#SomeModel
<div id="theDerpina">
<div>
//Some Stuff
#using (Ajax.BeginForm("Derpina1", "Controller", new { id = SomeModel.id }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "theDerpina",
InsertionMode = InsertionMode.Replace
}, new { id = "feedback-form" }))
{
//Some Stuff
<button type="submit" > Submit</button>
<br/>
<button type="button" > CloseWindow </button>
}
</div>
<div>
//More Stuff
#using (Ajax.BeginForm("Derpina2", "Controller", new { id = SomeModel.id }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "theDerpina",
InsertionMode = InsertionMode.Replace
}, new { id = "feedback-form" }))
{
//Different Stuff
<button type="submit" > Submit</button>
<br/>
<button type="button" > CloseWindow </button>
}
</div>
</div>
My two other Controller Actions:
public ActionResult Derpina1(int id)
{
SomeModel someModel = _GetModel(id);
if(ModelState.IsValid)
{
//DoStuff
return View("SomeOtherView");
}
else
{
return PartialView("Derp", someModel);
}
}
public ActionResult Derpina2(int id)
{
SomeModel someModel = _GetModel(id);
if(ModelState.IsValid)
{
//DoDifferentStuff
return View("SomeOtherView");
}
else
{
return PartialView("Derp", someModel);
}
}
When I open the Window once, everything works fine. However if I were to open the Window, close it, and then open it again then weird things happen. Let´s say for instance that I clicked the submit button for Derpina1, I would receive two calls to that particular Controller action. If I monitor the console in Firebug I see two separate calls to my controller action. Then the same thing would happen if I would close the Window one more time, open it again, and submit again, my controller action would now receive 4 calls to my controller action.
Perhaps you guys can point to the right direction. Should I open the Telerik Window in a different way, also should I use different method to return ModelError were that to happen? (because I´m faced with the same behaviour if I get a ModelError)
I managed to find out the solution after googling a while. All I did was creating a Window on the fly from within the script, and then destroying it after I have used it, like so:
function OpenTelerikWindow(arg) {
var url = '/Controller/Derp/';
$.ajax({
type: "GET",
url: url,
dataType: "html",
data: { id: arg }
success: function (data) {
var paymentWindow = $("<div id='PaymentWindow'></div>").tWindow({
title: "Payment",
contentUrl: '',
html: data,
modal: true,
resizable: false,
draggable: true,
width: 500,
height: 640,
onClose: function (e) {
e.preventDefault();
paymentWindow.data('tWindow').destroy();
}
});
paymentWindow.data('tWindow').center().open();
}
});
}

Passing Id from javascript to Controller in mvc3

How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});

generating pop up when button is clicked

when a submit button is clicked i want to generate a pop up showing the list of items. The code i tried to create pop up is as follows:`
Index View:
<script type="text/javascript">
$('#popUp').Hide();
$('#button').click(function () {
$('#popUp').click();
});
</script>
<div class="left-panel-bar">
#using (Html.BeginForm(FormMethod.Post))
{
<p>Search For: </p>
#Html.TextBox("companyName",Model);
<input id="button" type="submit" value="Submit" />
}
</div>
<div id="popUp">
#Html.ActionLink("Get Company List", "CreateDialog", "Company", null, new
{
#class = "openDialog",
data_dialog_id = "emailDialog",
data_dialog_title = "Get Company List"
});
</div>
but i got trouble using this code.. when i click the submit button it opens another page instead of popup. The controller code is as follows:
[HttpPost]
public ActionResult Index(Companies c)
{
Queries q1 = new Queries(c.companyName);
if (Request.IsAjaxRequest())
return PartialView("_CreateDialog", q1);
else
return View("CreateDialog", q1);
}
You could use AJAX:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
$('#popUp').html(result);
}
});
return false;
});
});
</script>
<div class="left-panel-bar">
#using (Html.BeginForm())
{
<p>Search For: </p>
#Html.TextBox("companyName", Model);
<input id="button" type="submit" value="Submit" />
}
</div>
<div id="popUp">
</div>
Now ehn the form is submitted, an AJAX request will be sent to the Index POST action and since inside you test if the request was an AJAX request it will return the _CreateDialog.cshtml partial view and insert it into the #popUp div. Also it is important to return false from the form submit handler in order to cancel the default even which is to redirect the browser away from the current page.

Resources