Hi I have problem with my MVC application.
I would like click on ActionLink > load data from server > and insert data to div in same page.
But my code still loads content on new page and I don`t have idea why. Anybody to help me ?
This is my Index.cshtml in HomeController,
#model IEnumerable<Kango_kmen.KangoKmenWS.WSEntityInfo>
#Content.Script("jquery-1.9.1.min.js", Url)
#Content.Script("jquery.unobtrusive-ajax.min.js",Url)
#Content.Script("jquery.unobtrusive-ajax.js",Url)
#Content.Script("myScript.js",Url)
#section Entities{
<table>
<tr>
<th>
<input type="submit" value="zobrazit" />
</th>
<th>
iD
</th>
<th>
name
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Ajax.ActionLink("..", "CheckEntity", new { id = item.iD },
new AjaxOptions{ UpdateTargetId="properties",
HttpMethod="GET",
InsertionMode=InsertionMode.InsertAfter,
})
</td>
<td>
#Html.DisplayFor(modelItem => item.iD)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
</tr>
<tr>
<td>
<div id="properties">
</div>
</td>
</tr>
}
</table>
}
#section PropertyInfo{
<p>Property info</p>
}
#section Properties{
<p>properties</p>
}
And here is my Controller in HomeController
public PartialViewResult CheckEntity(int id)
{
var model = WSConnect.getEntityInfo(id);
if(model !=null){
return PartialView("CheckEntity", model.property);
}
var modell = new WSEntityInfo[0];
return PartialView("CheckEntity", modell);
}
and ChecktEntity is the Partial view but everytime I click on ActionLink controller load url: /Home/ChceckEntity/1000 for exmaple on view data on this new page "(
There are 2 things wrong with your code:
You have included the jquery.unobtrusive-ajax.js script twice, once the minified version and once the standard version. You should include it only once
The jquery.unobtrusive-ajax.js is not compatible with jquery 1.9.1 because one of the breaking changes in jQuery 1.9 is that the .live() method was removed and the jquery.unobtrusive-ajax.js script relies on it. If you look at your javascript console you would see the following error: The .live method is undefined.. So if you want to use the unobtrusive AJAX functionality in ASP.NET MVC you will have to downgrade the version of jQuery. For example the 1.8.3 version should be fine.
So:
#model IEnumerable<Kango_kmen.KangoKmenWS.WSEntityInfo>
#Content.Script("jquery-1.8.3.min.js", Url)
#Content.Script("jquery.unobtrusive-ajax.min.js", Url)
#Content.Script("myScript.js", Url)
Also please learn how to debug your javascript code. Use a tool such as FireBug or Chrome developer toolbar where all those errors will be shown.
Related
I have a table with some column in a asp.net mvc core project.
My view file looks like this
<h1>Items</h1>
<div class="panel-body">
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Rating</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Items)
{
<tr onclick="location.href='#(Url.Action("ShowItemDetails", "Item", new {Id = item.FilmId}))'">
<td>#item.Id</td>
<td>#item.Title</td>
<td>#item.Rating</td>
<td>#Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id }) | #Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
</tr>
}
</tbody>
</table>
</div>
The problem is that when i click on a row, the controller method ShowItemDetails is called twice(!).
I can not see from the code above why this happens. Also, clicking on Edit or Rate this calls first ShowItemDetails and then immediately Edit or RateItem method in controller. Any suggestion how this can be solved?
Clicking on Edit or Rate this calls first ShowItemDetails and then immediately Edit or RateItem method because Edit is under a table row and on tablerow, you have called showitemdetails action.so, when you click on td , it gets first executed row action then td action.that's why it get called twice.
I hope, you want to show details and edit options with data of table and Edit is controller name.
Tweak your table code like below:
<tbody>
#foreach (var item in Model.Items)
{
<tr>
<td>#Html.ActionLink("Show Details","ShowItemDetails","Item",new {Id = item.FilmId})</td>
<td>#item.Id</td>
<td>#item.Title</td>
<td>#item.Rating</td>
<td>#Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id }) | #Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
</tr>
}
</tbody>
The problem seems to be caused be something i thought was irrelevant
having a null image cause the method to be called twice. Setting it to
solves this.
Need to add code to check for Model.Image != null
Very strange!!
In asp.net ajax, the partial view response replaces the html and only the partial view is rendered.
In the below snippet, when I click the ActionLink "Steps", the partial view is returned and replaces the Details.cshtml.
What I need is this partial view should replace only the "main-content-div" div.
Please help out. Thanks
View: Details.cshtml
<div class="main-body">
<table>
<tr>
<td class="left-sidebar extended">
#Ajax.ActionLink("Steps", "Steps", new { id = ViewBag.Id }, new AjaxOptions { AllowCache = false, UpdateTargetId = "main-content-div", InsertionMode=InsertionMode.Replace })
</td>
<td class="main-wrapper">
<div class="main-content" id="main-content-div">
This is the default stuff which I'll be replacing...
</div>
</td>
<td class="right-sidebar"></td>
</tr>
</table>
Action Method:
[HttpGet]
public PartialViewResult Steps(string id)
{
//reading model from db
return PartialView("~/Views/Author/Exercise/_StepsPartial.cshtml", Model);
}
Partial View:
#model IEnumerable<Model>
<div>
<div>
<input type="text" />
</div>
</div>
You need to add jquery.unobtrusive-ajax.min.js to your project for this to work.
Go to the Nuget Console Package Manager console and type:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
You then just need to add a reference at the top of your _Layout.cshtml or View to the relevant script:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
I'm current working on making a sort of wiki of plants. The first thing we started doing is the managment of the users in the site. For that we made this view that shows the results of a search from the database. The search works fine and the ViewData["datos"] returns what it should, and in this table we show the users (From the Model Usuario). In the end, for each user it should show a button that sends the Model for that user to another Controller. The problem is that the Controller receives an empty model.
Here's the code for the View. The input with the value Editar is the one that should send the model.
#model AtlasPlantasMedicinales.Models.Usuario
#{
ViewBag.Title = "Tabla";
}
#if (ViewData["datos"]!=null){
<table>
#foreach (var elemento in (List<AtlasPlantasMedicinales.Models.Usuario>)(ViewData["datos"]))
{
<tr>
<td>
#elemento.Nombre
</td>
<td>
#elemento.Carrera
</td>
<td>
#elemento.Institucion
</td>
<td>
#elemento.usuario
</td>
<td>
#elemento.correo
</td>
#using (Html.BeginForm("FormularioEditar", "Usuario", FormMethod.Post))
{
<td>#Html.HiddenFor(m => elemento) <input type="submit" value="Editar"></td>
}
</tr>
}
</table>
}
How can we send the model in elemento to the controller?
We have also tried making a Html.HiddenFor for each attribute in the model, but it still doesn't work.
Please keep in mind that me (and my teammmates) are completely new at ASP.NET MVC 4
This is a model binding problem. If you are willing to use the default model binder, use for loop instead of foreach. Your code will go something as as follows (Since you didn't post the Model/ViewModel, I will use ModelId as the property, and usuario as the value):
#for (int i = 0; i < (List<AtlasPlantasMedicinales.Models.Usuario>)(ViewData["datos"])).Count(); i++)
{
var elemento = (List<AtlasPlantasMedicinales.Models.Usuario>)(ViewData["datos"])).ElementAt(i);
<tr>
<td>
#elemento.Nombre
</td>
<td>
#elemento.Carrera
</td>
<td>
#elemento.Institucion
</td>
<td>
#elemento.usuario
</td>
<td>
#elemento.correo
</td>
#using (Html.BeginForm("FormularioEditar", "Usuario", FormMethod.Post))
{
<td>#Html.HiddenFor(m => m.ModelId, new { #Value = elemento.usuario }) <input type="submit" value="Editar"></td>
}
</tr>
}
Now, in the controller you will receive Usuario model with only the ModelId property initialized.
For more information about the model binding, I recommend you to this read this blog post by Scott Hanslman
I have a partial view, in my ASP.NET MVC4 web app. It's just a partial view designed to display a table, given a collection of entities. It looks like this:
#model ICollection<Portal.Models.Matter>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Last Accessed</th>
<th>Client</th>
</tr>
</thead>
<tbody>
#if (Model.Count > 0)
{
#Html.DisplayForModel()
}
else
{
<tr>
<td colspan="3" class="text-muted text-centered">There are no Matters to display.</td>
</tr>
}
</tbody>
</table>
I have a DisplayTemplate for Matter that is statically typed to the single Matter entity, and it handles rendering of each table row.
For some reason, when this partial is rendered, instead of using the Matter DisplayTemplate it just shows the following:
System.Collections.Generic.List`1[Portal.Models.Account]System.Collections.Generic.List`1[Portal.Models.Account]
Now, this partial is not even bound to a collection of Account entities. It's bound to a collection of Matter entities. So, why is #Html.DisplayForModel() trying to display for a collection of Accounts? At run time, using a debugger, I can see the Model is in fact a collection of Matter entities, not Account.
I render this partial using the following code:
#Html.Partial("~/Views/Matter/_Table.cshtml", Model.Client.Matters, new ViewDataDictionary())
I found a work around, or maybe a solution, not sure. Anyway, instead of using DisplayForModel on an ICollection, I iterate over the collection and use DisplayFor on each element.
For example ...
#model ICollection<Foo>
for (var item in Model)
{
#Html.DisplayFor(m => item)
}
I guess nothing is forcing you to use a property off of m in DisplayFor.
I am trying to render a table, using EditorFor, and a partialview, I think.
I have a model with a List<> property defined like this:
public List<TransactionSplitLine> TransactionSplitLines { get; set; }
The idea is that a user selects a few drop downs and enters a value into an edit box, and clicks a button. The model goes back to the controller, and the controller adds the entered values to the List<>
[HttpPost]
public ActionResult AccountTransaction(AccountTransactionView model)
{
var reply = CreateModel(model);
if (model.CategoryIds != null)
{
foreach (var c in model.CategoryIds)
{
reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = int.Parse(c) });
}
}
reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = 1 });
return View("AccountTransaction", reply);
}
Ignore the CreateModel. It simply sets up some data. Also, I am hardcoding data. This will eventually come from some form values.
The model is then returned to the same screen, allowing the user to ender more data. Any items in the List<> are read and a Table is rendered. I also have to store the current listen item values in hidden fields, so that they can be submitted back, along with the new data entered, so that the list can grow each time the user adds data.
The view is defined like this:
<table width="600">
<thead>
<tr class="headerRow">
<td>
Category
</td>
<td>
Sub Category
</td>
<td>
Amount
</td>
</tr>
</thead>
<tbody>
<%=Html.EditorFor(m=>m.TransactionSplitLines) %>
</tbody>
</table>
This is my first attempt with EditorFor...
My View is in a folder 'Views/BankAccount/AccountTransaction.aspx
I have created a ascx in Views/Shared/TransactionSplitLines.ascx
The code for the ascx is like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BudgieMoneySite.Models.TransactionSplitLine>" %>
<tr>
<td>
<%=Model.Category %>
<%=Html.HiddenFor(x => x.CategoryId)%>
</td>
<td>
<%=Model.SubCategory %>
<%=Html.HiddenFor(x => x.SubCategoryId)%>
</td>
<td>
<%=Model.Amount %>
<%=Html.HiddenFor(x => x.AmountValue)%>
</td>
</tr>
This is data
The 'This is data' is just test stuff, which is never rendered.
When I run this, all that happens is that my output is rendered as:
<table width="600">
<thead>
<tr class="headerRow">
<td>
Category
</td>
<td>
Sub Category
</td>
<td>
Amount
</td>
</tr>
</thead>
<tbody>
Test Category
</tbody>
</table>
It seems like the ascx isn't being used? I'd expect to see the 'This is data' text. But, nothing. Hopefully you can see an obvious fault?
Your editor template should be either:
~/Views/Shared/EditorTemplates/TransactionSplitLine.ascx
or:
~/Views/BankAccount/EditorTemplates/TransactionSplitLine.ascx
The name of the ascx is always the type name of the collection item (TransactionSplitLine and not TransactionSplitLines) and it should be situated at ~/Views/Shared/EditorTemplates or ~Views/ControllerName/EditorTemplates.
Or if you want to use a custom editor template name:
<%= Html.EditorFor(m=>m.TransactionSplitLines, "~/Views/foo.ascx") %>
Or use UIHintAttribute on your model.