Is not the way I want PartialViewResult - asp.net-mvc

I try something.I apologize in advance for my english.
My Action code;
public PartialViewResult showProduct()
{
var query = db.Categories.Where((c) => c.CategoryID == 4);
return PartialView("_EditCategory",query);
}
My view code:
#using (Ajax.BeginForm(
"showProduct",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "result"
}))
{
<input type="submit" value="Get" />
}
<div id="result">
</div>
When i pushed the submit button ( which value is get) the results return but in another page like http://localhost:57616/Home/showProduct but i want return to result div in index page.
Any one can help me?

So, how I handled this myself was something like this:
$(document).ready(function () {
var options = {
target: "#mytargetdiv",
url: '#Url.Action("Edit", "IceCream")',
};
$("#editIceCreamForm").submit(function () {
$(this).ajaxSubmit(options);
return false;
}
// other stuff
});
in other places, where I wanted to do in-place editing of things I'd do something like this:
<input type="button" id="someid" value="Edit" data-someid="#Model.SomeId"/>
and then some ajax like so:
$(function () {
$("#someid".click(function () {
var theId = $(this).data('someid');
$.ajax({
type: "GET",
data: "id=" + theId,
url: '#Url.Action("Edit", "Something")',
dataType: "html",
success: function (result) {
$('#targetdiv').html(result);
}
});
});
});
So, if you're not interested in using jQuery and want to use the MS Ajax stuff, are you including the MicrosoftAjax.js and MicrosoftMvcAjax.js files on the page? If you don't have those, I believe what will happen is it just does the default (non-Ajax) submit.

Related

How Bind Model data to Telerik Controls?

I am using bellow code to insert the data to db. While Clicking the save button the data should be bind to the model and needs to be posted to controller action . But the data is not bind to the model. What is the issue in the bellow code . Any please help me to solve the below issue.
#(Html.Kendo().TextBoxFor(model => model.Code)
.HtmlAttributes(new { placeholder = "Enter Code", required = "required",
validationmessage="Code is Required" })
)
<input type="button" title="Save" id="btnsave" value="Save" onclick="submit()"/>
<script>
function submit(data) {
debugger;
console.log("Cosoledata "+JSON.stringify(data))
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: { data: #Model },
dataType: "json",
success: function (response) {
}
});
}
</script>
data: { data: #Model },
In the JavaScript script, you can directly get the Model data via the #Model.
To send the model data to the controller method, you could create a JavaScript object, then use JQuery to get the related property value (such as Code), then send the object to the controller method.
Please refer the following sample:
View page:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#btnCreate").click(function () {
var review = {}; //create a JavaScript Object.
//user JQuery to get the entered value, and set the property value.
review.ReviewID = $("#ReviewID").val();
review.MovieID = $("#MovieID").val();
review.goreRating = $("#goreRating").val();
review.shockRating = $("#shockRating").val();
review.jumpRating = $("#jumpRating").val();
review.plotRating = $("#plotRating").val();
review.supernaturalRating = $("#supernaturalRating").val();
review.starRating = $("#starRating").val();
//if you want to send multiple objects, you could create an array.
//var reviewlist = [];
//reviewlist.push(review);
$.ajax({
url: "/Home/AddReview",
method: "Post",
data: { "reviewViewModel": review } , // { "reviewViewModel": reviewlist },
success: function (response) {
alert(response);
},
error: function (response) {
console.log("error");
}
})
});
})
</script>
}
Controller method:
[HttpPost]
public IActionResult AddReview(ReviewViewModel reviewViewModel)
{
if (ModelState.IsValid)
{
//do something
}
return View();
}
The result as below:

How to open a popup and post data to controller simultaneously using ajax call in MVC

I'm trying to implement search functionality in my Form View. The search window opens in a popup (in a partialView) and asks for search queries(figure). Now the user enters all the search fields and POST request is made and eventually popup window displays a table of search result.
Form View (which has the button to open popup window)
#Ajax.ActionLink("Search current form", "SearchAction", new { #id = "SearchBtn" }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess = "openPopup" }, new { #class ="btn btn-primary"})<br />
<div id="result" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#result").dialog({
autoOpen: false,
title: 'Search Window',
resizable:0,
width: 1000,
height: 700,
modal: true
});
});
function openPopup() {
$("#result").dialog("open");
}
</script>
SearchForm View (implemented as partial view)
#using (Html.BeginForm("SearchAction", "ViewModel", FormMethod.Post, new { #id = "searchform" }))
{
//some form elements
<div class="text-center">
<input type="submit" value="Go" class="btn btn-primary"/>
</div>
}
<div class="alert-danger">#ViewBag.emptyResult</div>
#if (Model != null)
{
//display the search results
}
Now to retain the popup I have to bind Go button to a ajax action in the same way as Form View. Also by reading this How to pass formcollection using ajax call to an action? I came to know that Ajax actions posts JSON data into the controller as opposed to key value pair which is easily accessible by FormCollection. So my question is how do I implement submit button(Ajax.Actionlink) in my search form so that it posts data into controller using FormCollection and retains the popup window as well.
Turns out I just needed to define a placeholder for the result table in my search popup.
<div id="showData" class="text-center table table-bordered bg-light"></div>
Now get your search results using Ajax call
function GetSearchResult() {
var searchParams = [];
//get search queries from textbox ids
$.ajax({
type: 'POST',
dataType: "json",
traditional: true,
data: {
s: searchParams
},
url: "/{controller name} /{action}",
success: function (result) {
var col = [];
if (isJson(result)) {
var sR = JSON.parse(result);
//create a html table using javascript and fill it which the result you got
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table); //table is what you created dynamically using javascript
}
else {
alert("No results found, Please try again");
}
}
});
}
Add this action in your controller
[HttpPost]
public JsonResult AjaxMethod(string value, string Id)
{
var updatedList = GetSearchResults(); //get search result from your repository
return Json(updatedList);
}
And as far as creating a html table thorugh javascript is concerned this helped me a lot!

Passing "data-" to controller

I have the following code...
HTML:
<button type="button" class="btn btn-primary" id="filterData"
data-filterString="#Model.LastName">Filter</button>
TypeScript:
$("button[id='filterData']").click(() => {
var dataList = [];
var filter = $(this).data("filterString");
$("input[class='personRecord']").each(function() {
dataList.push($(this).val());
});
var parameters = JSON.stringify({ "filterString": filter, "dataList":paymentList });
$.ajax({
url: "/Employee/FilterName",
data: parameters,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
});
Controller:
[HttpPost]
public void SendAll(string filterString, List<string> dataList) {
...
}
However, the variable filter keeps returning "undefined". How do you pass custom data items, data-filterString in this case?
In your jQuery, you can only use lower case values for the data method, even if your attributes are upper/mixed case. So you should write:
var filter = $(this).data("filterstring");
If you do use mixed case in your key, jQuery converts that to a dashed variable, so when you search for filterString, your attribute should be called data-filter-string.
$(function() {
console.log($('#test').data('filterstring'));
console.log($('#test').data('filterString'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test" data-filterString="value1" data-filter-string="value2"></div>

How do I get all values of checkbox those are checked using ajax/jQuery in asp.net mvc

Ajax post:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
// var vals = [];
// $('input:checkbox[name=Blanks]:checked').each(function () {
// vals.push($(this).val());
// });
// alert(vals);
//
var checkboxData = $(':checked').val();
$.ajax({
// Check the value.
type: 'POST',
url: '/Home/Extract',
data: { 'name': checkboxData },
// contentType: 'application/json; charset=utf-8', // No need to define contentType
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
});
Controller method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}
My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?
View:
<input type="button" id="btn" value="Extract" style="float:right "/>
#foreach (var m in (List<string>)ViewData["list"])
{
<ul>
<li>
<input type="checkbox" class="myCheckbox" name="Blanks" id="chk" value="#m"/>
<img src="#m" alt=""/>
First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.
Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:
$('#btn').click(function () {
var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
return $(this).val();
}).toArray();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ name: values }),
contentType: 'application/json',
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
return false;
});
And your controller action signature might look like this:
[HttpPost]
public ActionResult Extract(string[] name)
{
...
}
But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.

ASP.NET MVC 3 + jQuery Ajax JSON - Prevent JSON from opening in new page

I have an Action Method that returns a JSON-serialized object. The problem I'm having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here's the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
Here's the View (form):
#model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
#using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { #id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
#Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
#Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
#Html.TextBoxFor(x => x.DueDate, new { #class = "date" })
<script type="text/javascript">
$(function () {
$('.date').datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
And here's the javascript:
$(function () {
$('#add-assignment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
});
});
I have tried the event.stopPropogation() method, but didn't change my problem
EDIT: I've updated my javascript to the following, but I'm still getting the same result
$('#add-assignment-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
You need to return false; or event.preventDefault() to prevent the browser from submitting the form normally.
You have two options here,
Use Ajax.BeginForm() instead of Html.BeginForm() that you would use like
#using(Ajax.BeginForm( "AddAssignment", "Assignments",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "output"})) {
...
}
and get rid of the javascript code.
Or call event.prevendDefault() in
$('#add-assignment-form').submit(function (event) {
// ...
event.preventDefault();
});
Just specify
return false;
after your $.ajax() call
UPDATE
$(function () {
$('#add-assignment-form input[type=submit]').click(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
});
Have you checked if there are other javascript errors on the page that might be causing this unexpected behaviour? I would suggest Firebug for FF or Javascript Console for Chrome.
Also, I've noticed that sometime FF has issues if you don't specify the script type, so make sure your type is set to "text/javascript".
hth,
-covo

Resources