display view of another controller MVC5 - asp.net-mvc

I'm starting to develope in .NET and I have some questions.
I've created a view which uploads images to Azure. This view is included in a Controller called Document.
What I want is to display this view in another controller view. The view works perfectly alone, but when I try to reference it it gives me an error which I still don't know how to solve.
This is the view "Upload.cshtml"
#{
ViewBag.Title = "Upload";
}
<p>
#using (Html.BeginForm("Upload", "Documento", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="fileToUpload" name="image" />
<input type="submit" id="btnSubmit" value="Upload" />
}
</p>
<ul style="list-style-type: none; padding: 0;">
#foreach (var item in Model)
{
<li>
<img src="#item" alt="images" width="100" height="100" />
<a id="#item" href="#" onclick="deleteImage('#item');">Delete</a>
</li>
}
</ul>
<script type="text/jscript">
//get file size
function deleteImage(item) {
try {
var url = "/Documento/DeleteImage";
$.post(url, { Name: item }, function (data) {
window.location.href = "/Documento/Upload";
alert(data);
});
}
catch (e) {
alert("Error is :" + e);
}
}
</script>
And this is how I try to invoke the view from another Controller Index view:
#RenderPage("~/Views/Documento/Upload.cshtml");
#RenderBody();
And the error I get is because of the "#foreach(var item in Model)" sentence.
How should I do this?

It looks like you are missing your model at the top of your view. Something like this:
#model MyProject.Models.MyModel
Secondly your foreach loop needs a IEnumerable type. Is your model IEnumerable or #Model.SomeIEnumerable?
Lastly, whatever #item is in your loop should have seperate properties for your img src and anchor id attributes.
Either your code displayed isn't complete or you have a model issue. Here is any example of how to do what I think you are looking for.
View Model
public class MyModel
{
public string ProductId {get;set;}
public string ProductSrc {get;set;}
}
View
#model IEnumerable<MyModel>
<ul>
#foreach(item in Model)
{
<li>
<img src="#item.ProductSrc" />
<a id="#item.ProductId">Delete</>
</li>
}

Move the view to the Views/Shared folder instead. Then it will be available to all controllers without having to do anything special.
Also your view obviously expects a model to be passed in, so you have to do that from both controllers using the view.
In the controller that works I assume you have something like
return View("Upload", model);
or just
return View(model);
if you're action is named Upload. In the new action that is to use the same view, you have to create the model object and pass it to the view too.

Related

PartialViewResult on submit return another partial view

I have
public PartialViewResult CodePartial(string code){
...
return PartialView("anotherpartial");
}
which on has submit button and I want that on post executed anotherpartial partialviewresult. but instead it returns this partial view inside of CodePartial view. And on debugging it's not going inside of anotherpartial action.
How can I improve that?
CodePartial.cshtml
#model Kubeti.Models.Codes
#using (Ajax.BeginForm("CodePartial", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace }))
{
#Html.EditorFor(x => x.code)
#Html.ValidationMessageFor(x => x.code)
<input type="submit" value="OK" />
}
<div id="result" style="width: 500px; height:500px; border:1px solid red;">
index.cshtml
#Html.Partial("CodePartial")
#Html.Partial("anotherpartial")
Your method:
public PartialViewResult CodePartial(string code){
...
return PartialView("anotherpartial");
}
doesn't return 'to an action' as such. It simply returns the PartialView representation (meaning without the view being rendered with the layout, amongst other things) of the view that you specify.
If you want to return to another action, you need to post to that action or, alternatively, do something like this.

Pass Value of TextArea to Controller

I have the following code in a Partial View that is Rendered inside of another Partial View that is used as the _layout for all views in the project. There is a textarea for comments. I need to get the value of the Textarea to the Action Method in my controller. There is no ViewModel, so I don't know how to capture the contents.
<header>
<h4> Application Notes </h4>
#using (#Html.BeginForm("Comment", "LoanApplication"))
{
#Html.TextArea("Comment")
#*<textarea cols="100" rows="2" name="Comment" placeholder="Leave Comment ..."></textarea>*#
<input value="Add Comment" type="submit" />
}
</header>
The controller code is :
[HttpPost]
[Route("Comment")]
public async Task<ActionResult> Comment(string comment)
{
var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;
var applicationComment = new LoanApplicationComment
{
};
await loanApplicationServiceProxy.PutLoanApplicationCommentAsync(applicationComment);
return View();
}
It seems as if it should be something easy, but I can't seem to figure it out. Thanks for any and all assistance.
Change
string comment
To
string Comment
One other thing to try is to receive a FormCollection instead.

refreshing / reloading the PartialView inside the current view

I have a PartialView that is an image upload, and basically I am displaying some images and then the normal Upload buttons :-
#model MvcCommons.ViewModels.ImageModel
<table>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
<img src= "#Url.Content("/Uploads/" + item.FileName)" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
}
</table>
#using (Html.BeginForm("Save", "File", FormMethod.Post, new { enctype = "multipart/form-data" })) {
<input type="file" name="file" />
<input type="submit" value="submit" /> <br />
<input type="text" name="description" />
}
Now my idea is to have this in different pages. I tried it in 1 page already and is working fine, however when I Upload an image,
public ActionResult ImageUpload()
{
ImageModel model = new ImageModel();
model.Populate();
return View(model);
}
I want to go back to the "previous" View, ie the View that is hosting this partial view? When I do return View(model) as above, I get into the ImageUpload partial view which I do not want to.
Thanks for your help and time.
***UPDATE*********
I went for the simple route for the time being, and hard coded the actual View name
public ActionResult ImageUpload()
{
ImageModel model = new ImageModel();
model.Populate();
return View("~/Views/Project/Create.cshtml", model);
}
however I got an error :-
The model item passed into the dictionary is of type MvcCommons.ViewModels.ImageModel, but this dictionary requires a model item of type MvcCommons.Models.Project.
Use the overload that takes a string of the name of the view you want.
http://msdn.microsoft.com/en-us/library/dd460310
protected internal ViewResult View(
string viewName,
Object model
)
i.e.
return View("ViewName", model);
if you have this in different pages then you can inject context via the action paramaters;
public ActionResult ImageUpload(string parentViewName)
{
ImageModel model = new ImageModel();
model.Populate();
return View(parentViewName, model);
}
NOTE: You should only need to pass the views name not the path:
return View("Create", model);

MVC Ajax partial view not updating

I cannot get the partial view to update. If I refresh the page manually, I do see the incremented count. I tried similar approach without partial view inside the countDiv with action returning a random integer and the countDiv was getting updated just fine, so its something about the partial view:
Main view:
#using (Ajax.BeginForm("AddPositive", new RouteValueDictionary { { "id", Model.Id } },
new AjaxOptions() { UpdateTargetId = "countDiv"}))
{
<div>
<input type="submit" value="For" />
</div>
}
<div id="countDiv">
#Html.Partial("PollCounts")
</div>
PollsCounts partial view:
#model MyProj.Models.Poll
<div>Positive: #Model.PositiveCount</div>
<div>Negative: #Model.NegativeCount</div>
Action:
public PartialViewResult AddPositive(int id)
{
Poll poll = db.Polls.Find(id);
db.Entry(poll).State = EntityState.Modified;
poll.PositiveCount++;
db.SaveChanges();
return PartialView("CountsPartial", poll);
}
look in your action, you're returning the countsPartial instead of the pollsCount partial view

ASP.NET MVC ActionLink and post method

Can anyone tell me how can I submit values to Controller using ActionLink and POST method?
I don't want to use buttons.
I guess it has something with jquery.
If you're using ASP MVC3 you could use an Ajax.ActionLink(), that allows you to specify a HTTP Method which you could set to "POST".
You can't use an ActionLink because that just renders an anchor <a> tag.
You can use a jQuery AJAX post.
Or just call the form's submit method with or without jQuery (which would be non-AJAX), perhaps in the onclick event of whatever control takes your fancy.
You can use jQuery to do a POST for all your buttons. Just give them the same CssClass name.
Use "return false;" at the end of your onclick javascript event if you want to do a server side RedirectToAction after the post otherwise just return the view.
Razor Code
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.ID)
#Html.ActionLink("Save", "SaveAction", "MainController", null, new { #class = "saveButton", onclick = "return false;" })
}
JQuery Code
$(document).ready(function () {
$('.saveButton').click(function () {
$(this).closest('form')[0].submit();
});
});
C#
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveAction(SaveViewModel model)
{
// Save code here...
return RedirectToAction("Index");
//return View(model);
}
#Aidos had the right answer just wanted to make it clear since it is hidden inside a comment on his post made by #CodingWithSpike.
#Ajax.ActionLink("Delete", "Delete", new { id = item.ApkModelId }, new AjaxOptions { HttpMethod = "POST" })
Here was an answer baked into the default ASP.NET MVC 5 project I believe that accomplishes my styling goals nicely in the UI. Form submit using pure javascript to some containing form.
#using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", #class = "navbar-right" }))
{
<a href="javascript:document.getElementById('logoutForm').submit()">
<span>Sign out</span>
</a>
}
The fully shown use case is a logout dropdown in the navigation bar of a web app.
#using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", #class = "navbar-right" }))
{
#Html.AntiForgeryToken()
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="ma-nav-text ma-account-name">#User.Identity.Name</span>
<i class="material-icons md-36 text-inverse">person</i>
</button>
<ul class="dropdown-menu dropdown-menu-right ma-dropdown-tray">
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">
<i class="material-icons">system_update_alt</i>
<span>Sign out</span>
</a>
</li>
</ul>
</div>
}
ActionLink will never fire post. It always trigger GET request.
Use the following the Call the Action Link:
<%= Html.ActionLink("Click Here" , "ActionName","ContorllerName" )%>
For submitting the form values use:
<% using (Html.BeginForm("CustomerSearchResults", "Customer"))
{ %>
<input type="text" id="Name" />
<input type="submit" class="dASButton" value="Submit" />
<% } %>
It will submit the Data to Customer Controller and CustomerSearchResults Action.
This is taken from the MVC sample project
#if (ViewBag.ShowRemoveButton)
{
using (Html.BeginForm("RemoveLogin", "Manage"))
{
#Html.AntiForgeryToken()
<div>
#Html.Hidden("company_name", account)
#Html.Hidden("returnUrl", Model.returnUrl)
<input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from #account" />
</div>
}
}
Use this link inside Ajax.BeginForm
#Html.ActionLink(
"Save",
"SaveAction",
null,
null,
onclick = "$(this).parents('form').attr('action', $(this).attr('href'));$(this).parents('form').submit();return false;" })
;)
My Solution to this issue is a fairly simple one. I have a page that does a customer search one by the whole email and the other by a partial, the partial pulls and displays a list the list has an action link that points to a actionresult called GetByID and passes in the id
the GetByID pulls the data for the selected customer then returns
return View("Index", model);
which is the post method
This has been a difficult problem for me to solve. How can I build a dynamic link in razor and html that can call an action method and pass a value or values to a specific action method? I considered several options including a custom html helper. I just came up with a simple and elegant solution.
The view
#model IEnumerable<MyMvcApp.Models.Product>
#using (Html.BeginForm()) {
<table>
<thead>
<tr>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
</tr>
</thead>
#foreach (Product p in Model.Products)
{
<tr>
<td>#p.Name</td>
<td>#p.Price.ToString()</td>
<td>#p.Quantity.ToString()</td>
</tr>
}
</table>
}
The action method
public ViewResult Edit(Product prod)
{
ContextDB contextDB = new ContextDB();
Product product = contextDB.Products.Single(p => p.ProductID == prod.ProductId);
product = prod;
contextDB.SaveChanges();
return View("Edit");
}
The point here is that Url.Action does not care whether the action method is a GET or a POST. It will access either type of method. You can pass your data to the action method using
#Url.Action(string actionName, string controllerName, object routeValues)
the routeValues object. I have tried this and it works. No, you are not technically doing a post or submitting the form but if the routeValues object contains your data, it doesnt matter if its a post or a get. You can use a particular action method signature to select the right method.
I have done the same issue using following code:
#using (Html.BeginForm("Delete", "Admin"))
{
#Html.Hidden("ProductID", item.ProductID)
<input type="submit" value="Delete" />
}
This is my solution for the problem.
This is controller with 2 action methods
public class FeedbackController : Controller
{
public ActionResult Index()
{
var feedbacks =dataFromSomeSource.getData;
return View(feedbacks);
}
[System.Web.Mvc.HttpDelete]
[System.Web.Mvc.Authorize(Roles = "admin")]
public ActionResult Delete([FromBody]int id)
{
return RedirectToAction("Index");
}
}
In View I render construct following structure.
<html>
..
<script src="~/Scripts/bootbox.min.js"></script>
<script>
function confirmDelete(id) {
bootbox.confirm('#Resources.Resource.AreYouSure', function(result) {
if (result) {
document.getElementById('idField').value = id;
document.getElementById('myForm').submit();
}
}.bind(this));
}
</script>
#using (Html.BeginForm("Delete", "Feedback", FormMethod.Post, new { id = "myForm" }))
{
#Html.HttpMethodOverride(HttpVerbs.Delete)
#Html.Hidden("id",null,new{id="idField"})
foreach (var feedback in #Model)
{
if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
{
#Html.ActionLink("Delete Item", "", new { id = #feedback.Id }, new { onClick = "confirmDelete("+feedback.Id+");return false;" })
}
}
...
</html>
Point of interest in Razor View:
JavaScript function confirmDelete(id) which is called when the link generated with #Html.ActionLink is clicked;
confirmDelete() function required id of item being clicked. This item is passed from onClick handler confirmDelete("+feedback.Id+");return false; Pay attention handler returns false to prevent default action - which is get request to target. OnClick event for buttons could be attached with jQuery for all buttons in the list as alternative (probably it will be even better, as it will be less text in the HTML page and data could be passed via data- attribute).
Form has id=myForm, in order to find it in confirmDelete().
Form includes #Html.HttpMethodOverride(HttpVerbs.Delete) in order to use the HttpDelete verb, as action marked with the HttpDeleteAttribute.
In the JS function I do use action confirmation (with help of external plugin, but standard confirm works fine too. Don't forget to use bind() in call back or var that=this (whatever you prefer).
Form has a hidden element with id='idField' and name='id'. So before the form is submitted after confirmation (result==true), the value of the hidden element is set to value passed argument and browser will submit data to controller like this:
Request URL:http://localhost:38874/Feedback/Delete
Request Method:POST Status Code:302 Found
Response Headers
Location:/Feedback
Host:localhost:38874
Form Data X-HTTP-Method-Override:DELETE id:5
As you see it is POST request with X-HTTP-Method-Override:DELETE and data in body set to "id:5". Response has 302 code which redirect to Index action, by this you refresh your screen after delete.
I would recommend staying pure to REST principles and using an HTTP delete for your deletes. Unfortunately HTML Specs only has HTTP Get & Post. A tag only can a HTTP Get. A form tag can either do a HTTP Get or Post. Fortunately if you use ajax you can do a HTTP Delete and this is what i recommend. See the following post for details: Http Deletes
Calling $.post() won't work as it is Ajax based. So a hybrid method needs to be used for this purpose.
Following is the solution which is working for me.
Steps:
1. Create URL for href which calls the a method with url and parameter
2. Call normal POST using JavaScript method
Solution:
In .cshtml:
View
Note: the anonymous method should be wrapped in (....)()
i.e.
(function() {
//code...
})();
postGo is defined as below in JavaScript.
Rest are simple..
#Url.Action("View") creates url for the call
{ 'id': #receipt.ReceiptId } creates parameters as object which is in-turn converted to POST fields in postGo method. This can be any parameter as you require
In JavaScript:
(function ($) {
$.extend({
getGo: function (url, params) {
document.location = url + '?' + $.param(params);
},
postGo: function (url, params) {
var $form = $("<form>")
.attr("method", "post")
.attr("action", url);
$.each(params, function (name, value) {
$("<input type='hidden'>")
.attr("name", name)
.attr("value", value)
.appendTo($form);
});
$form.appendTo("body");
$form.submit();
}
});
})(jQuery);
Reference URLs which I have used for postGo
Non-ajax GET/POST using jQuery (plugin?)
http://nuonical.com/jquery-postgo-plugin/
jQuery.post() will work if you have custom data. If you want to post existing form, it's easier to use ajaxSubmit().
And you don't have to setup this code in the ActionLink itself, since you can attach link handler in the document.ready() event (which is a preferred method anyway), for example using $(function(){ ... }) jQuery trick.
Came across this needing to POST from a Search (Index) page to the Result page. I did not need as much as #Vitaliy stated but it pointed me in the right direction. All I had to do was this:
#using (Html.BeginForm("Result", "Search", FormMethod.Post)) {
<div class="row">
<div class="col-md-4">
<div class="field">Search Term:</div>
<input id="k" name="k" type="text" placeholder="Search" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-default">Search</button>
</div>
</div>
}
My Controller had the following signature method:
[HttpPost]
public async Task<ActionResult> Result(string k)

Resources