How could I set UpdateTargetId on jQuery ajax - c#

I want to render the partial view using ajax.
When I submit the button, the partial view must be rendered.
I could implemented it using ActionLink but I want to call the Action by JavaScript.
But the following code doesn't work. The Action is called but the partial view does not be rendered.
View
#section script{
<script type="text/javascript">
function test() {
$.ajax(
{
type: "POST",
url: "Test",
data: "",
success: function (result) { alert("OK!!"); },
error: function (req, status, error) {
alert("Damn!!");}
});
}
</script>
}
<input type="submit" onclick="test()" />
<div id="Container">
Controller
public ActionResult Test()
{
if (Request.IsAjaxRequest())
{
return PartialView("ViewUserControl1");
}
return View();
}
Partial View ViewUserControl1
Hello world
This works but is not what I want to do
#Ajax.ActionLink("click me", "Test", new AjaxOptions { UpdateTargetId = "Container" })

Your url may not be correct. It dependent on your routing settings
defined in Global.asax . But usually your url should look like
"/Home/Test" if your action is in HomeController. It's better to use
url helper for getting actions' urls:
...
url: '#Url.Action("Test", "Home")'
...
You can render your partial in next way:
...
success: function (result) { $('#elementId').html(result) },
...
Also if you want to update block, don't forget to clear it first and if it contains form with unobtrusive validation - parse form.

Related

Pass Model and Variables with AJAX

A partial view (_AddItem.cshtml) is called from the main view (Category.cshtml) in order to add existing items to the page on load.
I'm now adding AJAX so that an item can be added, to the page, by the user at the click of a button. When the form is subsequently submitted the item will be added to the model.
The partial view relies on the category model (activeCategoryModel) and two variables. Currently, these are successfully being passed from the view in the following way:
Category.cshtml
#Html.Partial(
"_AddItem",
activeCategoryModel,
new ViewDataDictionary(ViewData) { { "itemIndex", itemIndex }, { "itemLabel", itemLabel } }
);
My question is how can I pass the model (activeCategory) and these two variables when using AJAX? Below is the code I've started writing for the AJAX post:
Button and inputs added to view (Category.cshtml)
<input id="add-item-label" type="text" />
<input id="nextItemIndex" type="hidden" value="#activeCategoryModel.Items.Count" />
<button id="add-item" type="button">Add Item</button>
AJAX post added in javascript
This is not necessary fully functional code, I've just attempted to write an AJAX post with the variables in the 'data' parameter.
$("#add-item").click(function () {
var itemIndex = $("#nextItemIndex").val();
var itemLabel = $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem")',
data: '{{itemIndex: ' + itemIndex + '}, {itemLabel: ' + itemLabel + '}}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$("#nextItemIndex").val($("#nextItemIndex").val() + 1);
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
Partial view call added to Controller
I think this is where the model and variables need to be included in the partial view call.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
return PartialView();
}
Partial View (_AddItem.cshtml)
This has not been changed for the AJAX post.
#model CategoryModel
#{ int i = (int)ViewData["itemIndex"];}
#{ string l = (string)ViewData["itemLabel"];}
...
There are different ways in this case,
Example : Html.RenderPartial directly rendered partial action without ajax.
If you want to use Ajax to call partialView , you must be render
Html. Because PartialView returned Html.
I think the most important value in Ajax request is dataType and
the second important point is added returned html data in a div element
jQuery("#add-item").click(function () {
var dItemIndex = 1; //$("#nextItemIndex").val();
var dItemLabel = "Text"; // $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem","Home")',
data: { itemIndex: dItemIndex, itemLabel: dItemLabel },
dataType: "html",
//contentType: "application/json; charset=utf-8",
success: function (d) {
console.log("Success");
$("#partialData").html(d);
**// Create div in cshtml Page
// <div id="partialData"></div>**
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
At the controller side you can read parameters and fill in the content and send the PartialView as follows.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
ViewData["itemIndex"] = itemIndex;
ViewData["itemLabel"] = itemLabel;
return PartialView(new CategoryModel { Id = 5, Text = "Sample 5" });
}

How to pass data to controller action from view in asp.net mvc?

I am creating an asp.net application.
I have an image displayed inside the view of a controller action. When I click on an item in the view (say an image) I would like to pass some data (say ID) to a controller action.
I have the following code in the view:
#Url.Content("ActionName", "Controller");
I would like to send the data into the ActionName action of the Controller controller.
And the controller action looks as follows:
public ActionResult ActionName(string someParam)
{
return View();
}
I can call the controller action without a problem but I cannot pass the data. Thanks for help.
<a href='#Url.Action("MyAction", "MyController", new {id = "ID"})'>
<img src='#Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>
You can Add image in URL action or create onclick function for image and make Ajax request
<a href="#Url.Action("ActionName", "Controller", new {someParam = "value"})">
<img />
</a>
you can make an ajax call
an example below
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});

Request.IsAjaxRequest not woking mvc

when i am using Request.IsAjaxRequest(). i am not able to return view(). please check below code.
this is Action.
public ActionResult Index()
{
if (!Request.IsAjaxRequest()) {
return View("ajexview");
}
return view("About");
}
this is view
<script>
$(function () {
$("button").click(function () {
var car = { Make: 'Audi', Model: 'A4 Avant', Color: 'Black', Registered: 2013 };
$.ajax({
type: "POST",
url: "/home/index/",
data: car,
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
});
<button>Click me</button>
when i am posting about view is not able to return
First off, i'm not sure if your Index action will be hit by your ajax call at all. You are doing a post against a get action. To get the Request.IsAjaxRequest() to work as intended, either try creating another controller action and marking it with the HttpPost attribute like so,
[HttpPost]
public ActionResult Index(Car car)
{
if (!Request.IsAjaxRequest()) {
return PartialView("ajexview");
}
return View("About");
}
Note also that in the if (!Request.IsAjaxRequest()) block i'm returning "ajexview" as a PartialView.
or if your intention was to hit the get Index action then you will need to do an ajax 'get' request instead like
$.ajax({
type: "GET",
url: "/home/index/",
success: function (data) {
$('#result').html(data);
}
});
Be sure to Render scripts in the right place and order in your _layout.cshtml:
e.g. at the top:
...
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
... and the bottom:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/datatables")
#Scripts.Render("~/bundles/datatables")
<!-- etc. -->
#RenderSection("scripts", required: false)
</body>
</html>
Also be mindful of the construction of your BundleConfig.cs.

ASP MVC4 upload file without form but with partial view

Is it possible to upload a file using ASP.NET MVC4 with Razor without using forms (either BeginForm or <form>) in the view.
My problem is I have a partial view on the main view to show infomation (a log), if I use forms I can get the information about the file being uploaded either via the HttpPostFileBase or Request.Files, however my partial view refresh, refreshes the entire page and I end up only seeing the partial view. If I don't use forms the partial view updates correctly, but I'm missing all information about the file.
I've tried preventDefault() in the ajax (which updates the partial view). But I can't seem to get it to work.
Here is my code:
Controller:
[HttpPost]
public PartialViewResult FileUpload(MyViewModel vm)
{
vm.Log = new ScriptLog();
if (Request.Files.Count < 1)
{
vm.Log.Add("File information missing");
}
else if (Request.Files[0].ContentLength < 1)
{
vm.Log.Add("File empty");
}
else
{
// Upload file and fill log
vm.Log.Add("File uploaded successfully.");
}
return PartialView("Log", vm.Log);
}
View:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
#model ViewModels.MyViewModel
<input type="file" name="file" accept="application/vnd.ms-excel" />
<input id="uploadButton" type="submit" value="Upload" />
#*
Without the form (BeginForm or <form>) the partial view correctly updates in place.
But it is missing any file information.
With it I can get the file information but I can't update the partial view in place.
*#
<div id="log">
#{ if (Model != null)
{
Html.RenderPartial("Log", Model.Log);
}
}
</div>
<script>
$("input[id=uploadButton]").on("click", function (e) {
//e.preventDefault(); // preventing the default action
//alert("Here")
$.post("/MyContoller/FileUpload")
.done(function (partialResult) {
$("#log").html(partialResult);
})
});
</script>
Ok, so here is the solution:
$("input[id=uploadButton]").on("click", function (e) {
var fd = new FormData();
var input = document.querySelector("input");
//fd.append({name of you variable in ViewModel}, value)
fd.append('file', input.files[0]);
$.ajax({
url: '/MyContoller/FileUpload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
Here are some references:
MDN | Using FormData
jQuery | $.ajax()

Validation on Ajax loaded form - presenting back the validation summary

I am trying to validate a submitted form that is loaded in isolation to the rest of the page. I use validation all the time with my normal non ajax loaded content. I go on this principle:
Submit the form
pass the request from my controller to my service
Validate the object in the service
pass back to the controller a bool depending on the validation state
Present the original form back with validation summary if there are validation errors
Present a success page if there are no validation errors
That works fine on non-ajax content.
Now lets consider my issue. I have this kind of structure:
<div id="mainContent">
<div id="leftContent"></div>
<div id="rightContent"></div>
</div>
<script>
$.ajax({
url: baseUrl + "home/newApplicationForm/",
type: "GET",
success: function (data) {
$("#rightContent").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error displaying content");
}
});
</script>
This puts my blank application form on the right hand side of the page.. everything else on the page is left unchanged by that ajax.
So home/newapplicationform now displays the form that is wrapped with:
#model homelessRentals.Model.Application
#{
AjaxOptions options = new AjaxOptions{
HttpMethod = "Post",
UpdateTargetId = "AddApplication"
};
}
#using (Ajax.BeginForm(options)) {
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.EditorFor(model => model.YourName)
#Html.ValidationMessageFor(model => model.YourName)
</div>
<input type="submit" value="Add Application" id="saveMe"/>
}
This form now pings back to my controller:
[HttpPost]
public ActionResult AddApplication(Application app)
{
bool validated = _service.AddApplication(app);
if(validated)
{
return PartialView("SuccessApp");
}
return PartialView(app);
}
This will either return me to my form with validation errors shown or route me to my success page. This works to the extent that the logic is right, BUT I get presented the partial view in replacement of the whole page - it is not presented back in the 'rightContent' div.
I have tried submitting the form and catching the submission in jquery, then running something like this but I get the same behaviour:
$.ajax({
url: baseUrl + "home/AddApplication/",
data: "{'app':" + JSON.stringify(newApp) + "}",
type: "POST",
success: function (data) {
$("#rightContent").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error displaying content");
}
});
Can anyone help me with a better way to achieve this validation?
Many thanks
The UpdateTargetId is incorrect, this needs to point to rightContent rather than AddApplication.
#{
AjaxOptions options = new AjaxOptions{
HttpMethod = "Post",
UpdateTargetId = "rightContent"
};
There is no dom element with the id of AddApplication.

Categories

Resources