the razor view is not displaying a navigation property value - asp.net-mvc-3

i have the following action method:-
[HttpPost]
public ActionResult Create(int questionid, Answer a)
{
if (ModelState.IsValid)
{
repository.AddAnswer(a);
repository.Save();
return PartialView("_details",a);
}
return View(a);
and the folloiwng _details partila view:-
<td>
#Html.DisplayFor(modelItem => Model.Description)
</td>
<td>
#Html.DisplayFor(modelItem => Model.Answer_Description.description)
</td>
<td>
#Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = Model.AnswersID },
new AjaxOptions
{
Confirm = "Are You sure You want to delete this Answer ?",
HttpMethod = "Post",
UpdateTargetId = Model.AnswersID.ToString()
})
</td>
</tr>
the problem that i am facing is that the #Html.DisplayFor(modelItem => Model.Answer_Description.description) value is not being displayed automatically after an ajx call unless i refresh the web page., so what might be the problme?

I would suspect a lazy loading problem (hard to be sure with the infos you give, but)...
As Model.Description seems to be a primitive (string) Property, but Answer_Description.description is a primitive property of a navigation property.
Are you sure that the Answer_Description is correctly loaded ?
Edit : to be more precise : your action receives an Answer : does it have the Answer_Description.description when passed ?
If no, you should get the Answer_Description from database before returning View...

Related

Ajax Action Link instead of Html Action link in MVC 5

I have many select queries on my Page and few Action links based on them used gets another data tab wise.
Example on stack over flow when we see the profile of the user we see
summary questions answers tags badges etc.
If a user clicks on any one of the tab it hits the entire action and all the other sections of the pages hits the database which results in increase in load time of the page.To improve the performance I thaught to apply ajax,so after searching I got this example.
Partial View.
#model IEnumerable<AJAX.Models.tblStudent>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
<h2>Time is #DateTime.Now</h2>
Controller
public ActionResult Index()
{
return View();
}
public PartialViewResult Twenty()
{
var result = from r in db.tblStudents where r.Age == 20 select r;
return PartialView("_Country", result);
}
public PartialViewResult TwentyFive()
{
var result = db.tblStudents.Where(x => x.Age >= 25);
return PartialView("_Country", result);
}
Index View
#{
ViewBag.Title = "Home Page";
}
#Ajax.ActionLink("Age 20", "Twenty", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
#Ajax.ActionLink("Age 25", "TwentyFive", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<div id="StudentList"></div>
<h2>Time is #DateTime.Now</h2>
#section scripts{
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}
This works fine and have added date time to cross check whether the clicked page hits the database leaving the other sections of the page.Would like to know whether its a correct way of using Ajax in MVC. As have Ajax.ActionLink.
Note : this tutorial
it up to your application situation. You can see this post just i found.
In the amount of code you have to write (less with Ajax.ActionLink) and the level of control you need (more with Html.ActionLink and a jquery ajax call).
So it's amount of code vs level of control and functionality needed => up to you to decide which one you need.
Both approaches are perfectly fine. The Ajax.ActionLink uses the jquery.unobtrisuve-ajax script to AJAXify the anchor behind the scenes.
Personally I always use Html.ActionLink + jQuery.
collectted. See this links
link1
link2
link3

Access Html.ActionLink property in Controller file

I need to access practiceid property in my controller file please help how I can access this
Corporate
Tax & Employee Comp/Exec Benefits
Business Finance & Restructuring
Regulatory
My csHtml code is as follows:
#foreach (var facetData in Model.SearchResultItems.Facets.Select((x) => new { Item = x.Key, Index = x.Value }))
{
<tr>
<td>
#Html.ActionLink(#facetData.Index, "Search","Search", new { practiceid = #facetData.Item })
</td>
</tr>
}
and controller code is as follows:
public ActionResult Search(string practiceid)
{
}
But I'm not getting anything in my practiceid parameter.
See this question.
What you want to do is to add parameters to the tag, not to the link. Which means you should leave fourth argument null and use fifth instead. ie.
#Html.ActionLink(#facetData.Index, "Search","Search", null, new { practiceid = facetData.Item })
And the documentation for this helper method with focus on fifth parameter.
Add the extra null
#foreach (var facetData in Model.SearchResultItems.Facets.Select((x) => new { Item = x.Key, Index = x.Value }))
{
<tr>
<td>
#Html.ActionLink(#facetData.Index, "Search","Search", new { practiceid = facetData.Item }, null)
</td>
</tr>
}

Receiving an attempt was made to remove a relationship between x and x however one of the relationship's foreign keys

I have an MVC project and I have a case where i need to update a parent and multiple child entities at the same time. In the post action I am receiving "an attempt was made to remove a relationship between x and x however one of the relationship's foreign keys" which is strange, all I'm doing is update, I'm not droping any entity whatsoever. I am using Linq to SQL and MVC3. The pseudocode is like the following:
#model Project.Models.ParentModel
...
#using (Html.BeginForm()) {
#Html.Label("Parent property")
#Html.EditorFor(model => model.ParentProperty)
#foreach (var child in Model.Childs)
{
Html.RenderPartial("_EditChild", child)
// Which is nothing more than a label and an editor for a property like:
// #model Project.Models.ChildModel
// #Html.Label("Child property")
// #Hteml.EditorFor(model => model.ChildProperty)
}
...
}
The Action looks like:
public ActionResult Edit(int id, FormCollection collection)
{
var parent = new Parent();
TryUpdateModel(Parent()); // which updates the parent and the child properties correctly
dataContext.SubmitChanges();
}
Can anybody explaing this behavior. Once again, I'm not removing or dropping any child entities!
The binding over a list can be pretty nasty, I had some problems with it myself. I modified my list editing code to work with childs and tested it, it worked and the data is correctly bound and visible in the post action:
#model MvcApplication2.Models.Parent
#using (Html.BeginForm())
{
<table>
#{
<tr>
<td>
#Html.TextBoxFor(m => m.Text)
#Html.HiddenFor(m => m.ID)
</td>
</tr>
for (int i = 0; i < Model.Children.Count; i++)
{
<tr>
<td>
#Html.TextBoxFor(x => x.Children[i].Title)
#Html.HiddenFor(x => x.Children[i].ID)
</td>
</tr>
}
}
</table>
<div class="button">
<input class="submit" type="submit" name="btnSave" id="btnSave" value="Save" />
</div>
}
Controller for my test looks like this:
[HttpGet]
public ActionResult EditingChildren()
{
Parent parent = new Parent() { Text = "" };
parent.Children = new List<Child>();
parent.Children.Add(new Child() { Title = "" });
parent.Children.Add(new Child() { Title = "" });
parent.Children.Add(new Child() { Title = "" });
return View(parent);
}
[HttpPost]
public ActionResult EditingChildren(Parent parent)
{
// save parent with children
}
Editing my post about saving data back with linq to sql:
If you are not binding the ID on the view, it will be left empty in the object in the post method. That gives you troubles saving back the data.
I usally bind therefore the ID to an hidden field so it will not be empty any more (view code above edited and added HiddenFor beneath TextBoxFor).
Have also a look about updating data with linq to sql on this website:
http://davedewinter.com/2009/04/07/linq-to-sql-updating-entities/ (under Attach an Entity, Change Properties, Update)
and this post:
enter link description here

The error of can not find View in Ajax form

I ask a similar question here
So I add Some OnComplete Functions and Id to Ajax Forms, And there is:
This is My View:
#foreach(var item in Model) {
<tr id="TR#(item.Id)">
#{Html.RenderPartial("_PhoneRow", item);}
</tr>
}
_PhoneRow:
#model PhoneModel
#using(Ajax.BeginForm("EditPhone", new { id = Model.Id }, new AjaxOptions {
UpdateTargetId = "TR" + Model.Id,
OnComplete = "OnCompleteEditPhone"
}, new { id = "EditAjaxForm" + Model.Id})) {
<td>#Html.DisplayFor(modelItem => Model.PhoneNumber)</td>
<td>#Html.DisplayFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Edit" class="CallEditPhone" id="edit#(Model.Id)" /></td>
}
Controller:
public ActionResult EditPhone(long Id) {
//Get model by id
return PartialView("_EditPhoneRow", model);
}
public ActionResult SavePhone(PhoneModel model) {
//Save Phone, and Get Updatet model
return PartialView("_PhoneRow", model);
}
_EditPhoneRow
#model PhoneModel
#using(Ajax.BeginForm("SavePhone", new { id = Model.Id }, new AjaxOptions {
UpdateTargetId = "TR" + Model.Id,
OnComplete = "OnCompleteSavePhone"
})) {
<td>#Html.EditorFor(modelItem => Model.PhoneNumber)</td>
<td>#Html.EditorFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Save" class="SaveEditPhone" id="save#(Model.Id)" /></td>
}
And Oncomplete Scripts:
function OnCompleteEditPhone() {
$('input.SaveEditPhone').click(function () {
var id = $(this).attr("id").substring(4);
$('form#SaveAjaxForm' + id).trigger('submit');
});
}
function OnCompleteSavePhone() {
$('input.CallEditPhone').click(function () {
var id = $(this).attr("id").substring(4);
$('form#EditAjaxForm' + id).trigger('submit');
});
}
So Click Edit Worked perfect, Then Click Save Worked good also, But in second time when i click the Edit Button I have an Error in Post Action I copy the Firebug console here:
http://Mysite/members/editphone/7652 200 OK 582ms
http://Mysite/members/savephone/7652 200 OK 73ms
http://Mysite/members/editphone/7652 500 internal server error 136ms
<title>The view 'EditPhone' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...
So where is the problem? If I remove OnCompleteSavePhone The Edit button for second time not worked, and with this function I have an error that not make any sense, How Can I fix it? I actually load partial views by Ajax, And need the buttons of this views worked correctly, at first every thing is fine but after Ajax result They don't, I think to add some Oncomplete functions, but there is an error also.
Your previous question is answered now. You had broken markup. As a consequence of this you no longer need to care about any OnComplete events and doing some auto triggers, form submissions and stuff. This will be handled by the Ajax.BeginForm infrastructure automatically for you.

Can't set SelectedItem in DropDownList in my MVC3 view

I know that I can set the SelectedItem in my controller, but I can't figure out how to set it in my view. I'm working on a sort of flashcard (study guide) application and I have imported about 400 test questions. Now I want to write a page for the instructor to be able to select a "Category" for each question. I'd like them to be able to update the category for all the questions on one page. My model has a question entity that contains a foreign key field to the category entity (the field is called QuestionCategory). So, my view is based on the Question entity, but I'm sending over the list of Categories (there are 14) in the ViewBag (so I don't have to send a full SelectList over with each of the 400 questions. As my view is iterating thru the items in my View, I just want to add a SelectList that contains the 14 categories in my ViewBag and then set the SelectedItem based on the value of item.QuestionCategory. I can't make it work.
Here's my controller action:
public ActionResult Index()
{
var context = new HBModel.HBEntities();
var query = from q in context.tblQuestions.Include("tblCategory") select q;
var questions = query.ToList();
ViewBag.Categories = new SelectList(context.tblCategories, "CategoryID", "CategoryName");
return View(questions);
}
Here's some of the things I've tried in the view (with associated error messages in the comments)
#model IEnumerable<HBModel.tblQuestion>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Question
</th>
<th>
Answer
</th>
<th>
AnswerSource
</th>
<th>
Category
</th>
<th>
Action
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.Question
</td>
<td>
#item.Answer
</td>
<td>
#item.AnswerSource
</td>
<td>
#item.tblCategory.CategoryName
#*This one works, but cannot initialize the selected item to be current database value*#
#Html.DropDownList("Categories")
#*compile error - CS0200: Property or indexer 'System.Web.Mvc.SelectList.SelectedValue' cannot be assigned to -- it is read only*#
#*#Html.DropDownListFor(m => item.QuestionCategory, (ViewBag.Categories as SelectList).SelectedValue = item.QuestionCategory)*#
#*error {"DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'CategoryId'."}*#
#Html.DropDownListFor(m => item.QuestionCategory, new SelectList(ViewBag.Categories, "CategoryId", "CategoryName"))
#*error - {"DataBinding: 'System.Char' does not contain a property with the name 'CategoryId'."}*#
#Html.DropDownListFor(m => item.QuestionCategory, new SelectList("Categories", "CategoryId", "CategoryName"))
)
</td>
<td style="width: 100px">
#Html.ActionLink("Edit", "Edit", new { id = item.QuestionID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.QuestionID })
</td>
</tr>
}
</table>
Of course, if I can get this to work, I'll need to try and add an action to go back to the controller and update all the records, but I'll just be happy to resolve my current issue.
I would really appreciate any help on this - Thanks!
You need to explicitly create the options in the select tag, using #Html.DropDownList, as follows (taken from a working app):
#Html.DropDownListFor(model => model.IdAccountFrom, ((IEnumerable<FlatAdmin.Domain.Entities.Account>)ViewBag.AllAccounts).Select(option => new SelectListItem {
Text = (option == null ? "None" : option.AccountName),
Value = option.AccountId.ToString(),
Selected = (Model != null) && (option.AccountId == Model.IdAccountFrom)
}), "Choose...")
#Html.ValidationMessageFor(model => model.IdAccountFrom)
You obviously need to change to the properties on your #Model.
NOTE:
This code was auto-generated by the MvcScaffolding NuGet package when I scaffolded a controller.
This package requires you to use Entity Framework Code First POCO classes for your entities. These are easy to generate from an existing database using the Entity Framework Power Tools CTP.
With MVC, you need to spend some time researching the tooling that is out there to help you generate the stuff that you need. Using these tools is a great way to get started and to see how to do things. You can then tweak the output to your heart's content.

Resources