Insert Data Into My DB trouble - asp.net-mvc

This is the View code, this view will show a list of preInscription Demande and two button Valide and Delete the first one it allow Webmaster To Inscription and the seconde one to Refuse Demande.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<J2V.Models.preinscrit>>" %>
// some Html Code
<% foreach (var item in Model) { %>
<li>
<div class="listinfo">
<h3>
<%: Html.DisplayFor(modelItem => item.Nag) %>
</h3>
<p>
<%: Html.DisplayFor(modelItem => item.Idag) %>
</p>
<span class="price"> <%: Html.DisplayFor(modelItem => item.Adrag) %> <%: Html.DisplayFor(modelItem => item.Vilag) %> <%: Html.DisplayFor(modelItem => item.Gov) %></span> <span class="media">Tel : <%: Html.DisplayFor(modelItem => item.Telag) %> |</span> <%: Html.DisplayFor(modelItem => item.Mailag) %>
</div>
<div class="listingbtns">
<span class="listbuttons"><%: Html.ActionLink("Valide", "Valide", new {mod= item}) %> |</span>
<span class="listbuttons"><%: Html.ActionLink("Supprime", "Delete", new { id=item.Idag }) %></span>
</div>
<div class="clear">
</div>
</li>
<% } %>
This is the "Valide" Action it allow To Validate preinscription and add Data to Agence Table and user table:
[HttpGet]
public ActionResult Valide(Models.preinscrit model )
{
var db = new Models.J2VEntities();
Models.agence ag = new Models.agence();
Models.user user = new Models.user();
ag.Adrag = model.Adrag ;
ag.Gov = model.Gov ;
ag.Idag = model.Idag;
ag.Mailag = model.Mailag;
ag.Nomag = model.Nag;
ag.Vilag = model.Vilag;
user.IsAdmin = false;
user.iduser = model.Idag;
user.password = Models.LogModel.register.CreateRandomPassword();
db.AddTouser(user);
db.AddToagence(ag);
return View("index");
}
When I click on Valide on my view page I get this error :
System.NullReferenceException
at this line ag.Adrag = model.Adrag ;

no need to use form. use actionlink to send item.id.
<span class="listbuttons"><%: Html.ActionLink("Valide", "Valide", new {id= item.id}) %> |</span>
and get id in valide action and get the model in your database by item.id
public ActionResult Valide(int id )
{
var db = new Models.J2VEntities();
Models.agence ag = new Models.agence();
Models.user user = new Models.user();
//select from databese by id and valide
ag.Adrag = model.Adrag ;
ag.Gov = model.Gov ;
ag.Idag = model.Idag;
ag.Mailag = model.Mailag;
ag.Nomag = model.Nag;
ag.Vilag = model.Vilag;
user.IsAdmin = false;
user.iduser = model.Idag;
user.password = Models.LogModel.register.CreateRandomPassword();
db.AddTouser(user);
db.AddToagence(ag);
return View("index");
}
this code is from my project :
//select list by id
public IEnumerable<makale> select_makaleler_by_kategori(int kategori_id)
{
IEnumerable<makale> makale = (from m in entity.makale
where m.kategori_id == kategori_id
orderby m.olusturma_tarihi
select m).ToList<makale>();
return makale;
}
//select one element by id
public makale select_makale(int makale_id)
{
makale makale = (from m in entity.makale
where m.makale_id == makale_id
select m).SingleOrDefault();
return makale;
}

you are using ActionLink for the wrong reason , it isn't used for passing data , you should make a <form> and then submit it using <input type='submit' />
the problem happens because the 3rd parameter in the ActionLink() is the routing values that works with the routing rules , its not used for sending data
from the code sample i think the user didnt enter anything the view just for showing the page
if that is the case then just pass an id to the ActionLink and in the Controller action query again all the information from the database using the id
never depend on passing parameter used for showing purpose from page to page , a hacker can easily break your app
so if you dont want information from the user just pass the id then query again in the other page

Related

How do I display results for one Id on a partial View MVC5

I am trying to display reservations for the current logged in restaurant but I am getting the following error.
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[RestaurantApplication.Models.Restaurant]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[RestaurantApplication.Models.RestaurantReservationEvent]'.
Here is my controller
public ActionResult RestaurantReservationsPartialView()
{
string currentUserId = User.Identity.GetUserId();
var restaurantID = (from r in db.Restaurants
where r.OwnerId == currentUserId
select r).ToList();
ViewBag.RestaurantId = restaurantID;
return PartialView("_RestaurantReservations", restaurantID);
And this is the view Calling the PartialView
<div style="padding-top: 50px;">
#Html.Action("RestaurantReservationsPartialView")
</div>
Here is the Partial view which I want to display the list of reservations for the current logged in restaurant.
#if (ViewBag.numReservations > 0 && ViewBag.ReservationStatus == "Pending")
{
<center><p id="pendingReservations">Here are your pending reservations</p>
</center>
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4 col-sm-4 col-xs-6">
<div class="panel panel-primary">
<div class="panel-heading">
<center><h1 class="panel-title">#Html.DisplayFor(modelItem => item.BookersName)</h1></center>
</div>
<div class="panel-body">
<h3 style="font-size: 16px">Booking Description: #Html.DisplayFor(modelItem => item.BookingDesc) <br />
Number of people: #Html.DisplayFor(modelItem => item.BookingNumberOfPeople)</h3>
<h3 style="font-size: 15px">
<h>Booking Date: #Html.DisplayFor(modelItem => item.BookingDate) at</h>
<h>#Html.DisplayFor(modelItem => item.BookingStartTime)</h>
</h3>
</div>
<div class="panel-footer">
<center>#Html.ActionLink("Accept", "AcceptReservation", new { id = item.RestaurantReservationEventID }, new { #class = "btn btn-success btn-xs" }) #Html.ActionLink("Decline", "DeclineReservation", new { id = item.RestaurantReservationEventID }, new { #class = "btn btn-danger btn-xs" })</center>
</div>
</div>
</div>
}
}
First of all, you are not calling a partial view from your main view, but invoking an action method using Html.Action method which returns a partial view result.
Your RestaurantReservationsPartialView action method is passing a list of Restaurant objects to it's (partial) view. But from the error message , it looks like your partial view is strongly typed to a list of RestaurantReservationEvent objects. You are getting this model type mismatch error because you are passing a wrong type to the partial view.
The solution is to pass the correct type. Since you want to pass the reservation for a specific restaurant, You probably want to accept the restaurant id as a parameter of your action method, use that to get the reservation events and pass that to the view.
Something like this.
public ActionResult RestaurantReservationsPartialView(int id)
{
var events = db.RestaurantReservationEvents.Where(x=>x.RestaurantId==id).ToList();
return View(events);
}
Assuming RestaurantReservationEvents is a property on your DbContext of type DbSet<RestaurantReservationEvent>. Please update the linq expression which returns a list of Restaurant to match with your situation
Now make sure you are passing the restaurant id when calling the action method.
<div style="padding-top: 50px;">
#Html.Action("RestaurantReservationsPartialView",,new { id=3})
</div>
Here i hard coded the Id value to 3.You may replace it with a variable which has the real value.

ASP.NET MVC 3 validation problem

I have 2 or more forms with different one hidden value like:
<div class="comment-body">
<% using (Html.BeginForm(Model.ActionName, "Home", Model.RouteValues, FormMethod.Post, new { id = "FormAddComment", name = "FormAddComment" }))
{ %>
<% = Html.ValidationSummary(false) %>
<fieldset>
<% if (Model.CommentParentID != null)
{
htmlAttributes = new { placeholder = "Add a reply...", id = "Comment" };
postButtonTitle = "Post Reply";
%>
<input type="hidden" name="CommentParentID" id="CommentParentID" value="<% = Model.CommentParentID.ToString() %>" />
<%} %>
<% = Html.TextAreaFor(model => model.Comment, htmlAttributes)%>
<% = Html.ValidationMessageFor(model=>model.Comment) %>
<input type="submit" value="<% = postButtonTitle %>" class="small blue awesome noborder"
border="0" />
<% if (Model.CommentParentID != null)
{%>
<a class="hide-sub-comment" href="javascript:void(0);">Cancel</a>
<%} %>
</fieldset>
<%} %>
</div>
Problem is when I try to validate entered value I got the validator message twice. When I add text and click "post" again - one validator is hidden, but page is not valid yet. Why and how to solve it?
Thanks
Modifying answer since you changed the question.
You could do something like this
<script type="text/javascript">
$(document).ready(function () {
$("#NotHiddenComment").change(function () {
var temp = $("#NotHiddenComment").val();
$("#HiddenCommentID").text(temp);
});
});
</script>
This will make sure both fields have the same value so you do not get validation errors.

How to pass the ParentNode Value from the JQuery TreeView to the Controller method on ASP.NET MVC Page?

I have an ASP.NET MVC page that has left Menu Navigation that is built dynamically using JQuery Treeview Control.
This Treeview has the list of ProductNames as the Parent Node(For Example: 10 Products). Each of these Products have a ChildNode as DocTypeName(For Example: 3 DocTypeNames).
Here When the user clicks on ParentNode, it expands and shows DocTypeNames. When the User Clicks on DocTypeName, it loads the partialView by calling the controller ActionResult DocumentDetails through Ajaxy way.
From the below code I am able to read the DocTypeName that is clicked. But I am not able to read the ProductName. It says "Undefined".
Anyone has any idea how to pass the Parent ProductName to the controller?
NavigationProducts.ascx Page:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MedInfoDS.Controllers.ProductViewModel>" %>
<script type="text/javascript">
$(document).ready(function () {
$(".docId").click(function () {
alert("DocTypeName: " + this.id);
alert("ProductName: " + this.ProductName); //Error throwing here "Undefined"
$("#docDetails").load('<%= Url.Action("DocumentDetails") %>', { ProductName: "darbepoetin alfa", DocTypeName: this.id }, function (responseText, status) {
});
return false;
});
});
<div id="treecontrol">
<a title="Collapse the entire tree below" href="#">Collapse All</a> | <a title="Expand the entire tree below"
href="#">Expand All</a> | <a title="Toggle the tree below, opening closed branches, closing open branches"
href="#">Toggle All</a>
<div id="divByProduct">
<ul id="red" class="treeview-red">
<% foreach (var item in Model.Products)
{ %>
<li><span>
<%=item.Name%></span>
<ul>
<%foreach (var item1 in Model.DocTypes) { %>
<li><span>
<%= Html.ActionLink(item1.DocTypeName, "Products", new { ProductName = item.Name, DocTypeName = item1.DocTypeName })%>
<br />
<a class="docId" href="#" id="<%=item1.DocTypeName%>"><%= item1.DocTypeName%></a>
<%= Html.Hidden("ProductName", item.Name)%>
</span></li>
<% } %>
</ul>
</li>
<% } %>
</ul>
Controller Method:
// Response to AJAXy call to populate details for given ProductName and DocType
[HttpPost]
public virtual ActionResult DocumentDetails(string ProductName, string DocTypeName)
{
var entities = new MIDSContainer();
if (ProductName == null) return View();
int ProductId = (entities.Products.FirstOrDefault(p => p.Name == ProductName)).ProductId;
int DocTypeId = (entities.DocTypes.FirstOrDefault(d => d.DocTypeName == DocTypeName)).DocTypeId;
var documents = (from d in entities.Documents.Where(p => p.ProductId == ProductId && p.DocTypeId == DocTypeId && p.AvailableForUse == true && p.Status == "Approved") orderby (d.Description) select d).ToList();
return View(documents);
}
Try to add this to the data that you send to the server:
ProductName: $(this).siblings(":hidden").val()
But you shoud definitely avoid generating multiple elements with the same id!
if Html.Hidden("ProductName", item.Name) renders a hidden field with id ProductName then you might have multiple elements with the same ID on one page and therefore the lookup for it might return undefined.
Otherwise the lookup jQuery query is just $("#ProductName").val()

RadioButtonFor, EditorFor, xxxFor on Property passed into Partials

Many of the properties on my model need to be represented a simple group of Yes/No radio buttons. I need to check the corresponding radio button for pre-entered values. I went with a partial. Here's what I did:
RadioButtonsYesNo.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KeyValuePair<string,string>>" %>
<div id="<%:Model.Key %>">
<%: Html.ValidationMessage(Model.Key)%>
<ul class='RadioButtonsYesNo'><li>
<%: Html.RadioButton(Model.Key, "Yes", Model.Value == "Yes", new { id = Model.Key + "_Yes" })%>
<label for='<%: Model.Key %>_Yes'>Yes</label>
</li><li>
<%: Html.RadioButton(Model.Key, "No", Model.Value == "No", new { id = Model.Key + "_No" })%>
<label for='<%: Model.Key %>_No'>No</label>
</li></ul>
</div>
Usage
<% Html.RenderPartial("RadioButtonsYesNo", new KeyValuePair<string, string> ("MyProp",Model.MyProp)); %>
Is there a best practice for passing in the property of interest and having RadioButtonFor render correctly?
Thanks.
Or in Razor:
#{
var yesRadioName = Model.Key + "_Yes";
var noRadioName = Model.Key + "_No";
#Html.RadioButtonFor(m => m.Key, true, new { #id = yesRadioName })
#Html.Label(yesRadioName , "Yes")
#Html.RadioButtonFor(m => m.Key, false, new { #id = noRadioName })
#Html.Label(noRadioName, "No")
}
Why not using RadioButtonFor in an editor template:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% string name = ViewData.TemplateInfo.GetFullHtmlFieldId(""); %>
<div id="<%: name %>">
<%: Html.ValidationMessageFor(x => x) %>
<ul class="RadioButtonsYesNo">
<li>
<%: Html.RadioButtonFor(x => x, "Yes", new { id = name + "_Yes" }) %>
<label for="<%: name %>_Yes">Yes</label>
</li>
<li>
<%: Html.RadioButtonFor(x => x, "No", new { id = name + "_No" }) %>
<label for="<%: name %>_No">No</label>
</li>
</ul>
</div>
And then:
<%: Html.EditorFor(x => x.MyProp) %>

ASP.NET MVC Passing Data from View to Controller

I have a view with a grid that contains items added to a workstation. The user can select an item from a drop down list and click an action link which calls a controller that adds that item to the workstation. I can make it work by reading the FormCollection object in the Post action of the controller.
<p>
<% using(Html.BeginForm("AddItem", "Home")) { %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("ItemID", Model.ItemsList) %>
<%= Html.Hidden("WorkstationID", Model.Workstation.RecordID) %>
<input type="submit" value="Submit" />
<% } %>
</p>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(FormCollection formValue)
{
long workstationId = Convert.ToInt64(formValue["WorkstationID"]);
long itemId = Convert.ToInt64(formValue["ItemID"]);
Workstation workstation = itilRepository.FindWorkstation(workstationId);
Item item = itilRepository.FindItem(itemId);
itilRepository.AddItem(workstation, item);
itilRepository.Save();
return Content("Item added successfully!");
}
What I want to do is be able to submit the two parameters the workstationId and itemId to the controller using Ajax.ActionLink and have the new item that was added get inserted into the grid. I am rendering the grid like this:
<table>
<tr>
<th></th>
<th>
Name
</th>
<th>
Service Tag
</th>
<th>
Serial Number
</th>
</tr>
<% foreach (var item in Model.Items) { %>
<tr>
<td>
<%= Html.ActionLink("Edit", "ItemEdit", new { id = item.RecordID }) %> |
<%= Html.ActionLink("Details", "ItemDetails", new { id = item.RecordID })%>
</td>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td>
<%= Html.Encode(item.ServiceTag) %>
</td>
<td>
<%= Html.Encode(item.SerialNumber) %>
</td>
</tr>
<% } %>
</table>
The problem I have is when I submit using the ActionLink I can't figure out how to pass in the parameters to the controller and how to update the grid without reloading the entire view.
I would really appreciate some help with this or even a link to a tutorials that does something similar.
Thank You!
This is the working version, the one problem is that when the controller returns the partial view that is all that gets rendred the actual page is gone.
<% using (Ajax.BeginForm("AddItem", null,
new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
},
new { #id = "itemForm" } ))
{ %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("itemId", Model.ItemsList) %>
<%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>
Submit
<div id="ResultsGoHere">
<% Html.RenderPartial("WorkstationItems", Model.Items); %>
</div>
<% } %>
Not sure what the cause is, the replace was working correctly before but the controller wasn't getting the drop down value. Now the controller is getting the value but the partial view that is returned replaces the entire page.
The Action Method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(string workstationId, string itemId)
{
long lworkstationId = Convert.ToInt64(workstationId);
long litemId = Convert.ToInt64(itemId);
Workstation workstation = itilRepository.FindWorkstation(lworkstationId);
Item item = itilRepository.FindItem(litemId);
IQueryable<Item> items = itilRepository.AddItem(workstation, item);
itilRepository.Save();
return PartialView("WorkstationItems", items);
}
This is the HTML for the View that does all the work:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ITILDatabase.Models.WorkstationFormViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Workstation Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<link type="text/css" href="/../Content/css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/../Content/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/../Content/js/jquery-ui-1.7.2.custom.min.js"></script>
<h2>
Workstation Details</h2>
<fieldset>
<legend>Fields</legend>
<p>
Record ID:
<%= Html.Encode(Model.Workstation.RecordID) %>
</p>
<p>
Name:
<%= Html.Encode(Model.Workstation.Name) %>
</p>
<p>
Description:
<%= Html.Encode(Model.Workstation.Description) %>
</p>
<p>
Site:
<%= Html.Encode(Model.Workstation.Site.Name) %>
</p>
<p>
Modified By:
<%= Html.Encode(Model.Workstation.ModifiedBy) %>
</p>
<p>
Modified On:
<%= Html.Encode(String.Format("{0:g}", Model.Workstation.ModifiedOn)) %>
</p>
<p>
Created By:
<%= Html.Encode(Model.Workstation.CreatedBy) %>
</p>
<p>
Created On:
<%= Html.Encode(String.Format("{0:g}", Model.Workstation.CreatedOn)) %>
</p>
</fieldset>
<fieldset>
<legend>People</legend>
<% Html.RenderPartial("WorkstationPeople", Model.People); %>
</fieldset>
<fieldset>
<legend>Positions</legend>
<% Html.RenderPartial("WorkstationPositions", Model.Positions); %>
</fieldset>
<fieldset>
<legend>Items</legend>
<% using (Ajax.BeginForm("AddItem", "Home", null,
new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
},
new { #id = "itemForm" } ))
{ %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("itemId", Model.ItemsList) %>
<%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>
Submit
<div id="ResultsGoHere">
<% Html.RenderPartial("WorkstationItems", Model.Items); %>
</div>
<% } %>
</fieldset>
<br />
<p>
<%=Html.ActionLink("Edit", "WorkstationEdit", new { id = Model.Workstation.RecordID }) %>
|
<%=Html.ActionLink("Back to List", "Index") %>
</p>
</asp:Content>
What result are you expecting from the AJAX call?
You could use the AjaxHelper object's helper methods instead of the HtmlHelper to render the link. For example, to get new content with an AJAX HttpPOST call and insert it into a <div> with the id set to ResultsGoHere you render the following link:
<%= Ajax.ActionLink("Edit", "ItemEdit",
new {
itemId = item.RecordId,
workstationId = myWorkStationId
},
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="ResultsGoHere",
InsertionMode = InsertionMode.Replace
}) %>
In your AcionMethod, you can simply test on Request.IsAjaxRequest() to decide what to return:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ItemEdit(string itemId, string workstationId) {
// edit the item and get it back
if (Request.IsAjaxRequest()) {
return PartialView("SingleItem", item);
}
return RedirectToAction("ItemEdit", new { itemId = item.RecordId, workstationId = workstationId });
}
// fallback for get requests
public ActionResult ItemEdit(string itemId, string workstationId)
{
// do stuff and return view
}
This is how you could do it using the Ajax.BeginForm() method instead:
<% using (Ajax.BeginForm("ItemEdit", null, new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
}, new { #id = "itemForm" } )
{ %>
<p>
<%= Html.DropDownList("itemId") %></p>
<p>
<%= Html.DropDownList("workstationId") %></p>
<p>
Submit
</p>
<% } %>
Please note that the code is in its current state in no way fully functional - the dropdownlists don't get their items from anywhere, there is no <div> to take care of the results from the AJAX request, and the onclick attribute on the link that submits the form requires that jQuery is included (in which case it is way better to give the link an id and add a click() event handler to it from a separate js file...)
EDIT: Oh, and I haven't verified that it is OK to pass a null value to the routeValues parameter. If not, just supply the controller and action names, and you'll be fine.
how can you pass the model from the view to the post create action of the controller using ajax.actionlink?
Here, as of my knowledge, we can pass data from View to Controller in two ways...
Using Formcollection built in keyword like this..
[HttpPost]
public string filter(FormCollection fc)
{
return "welcome to filtering : "+fc[0];
(or)
return "welcome to filtering : "+fc["here id of the control in view"];
}
FormCollection will work only when you click any button inside a form. In other cases it contains only empty data
Using model class
[HttpPost]
public string filter(classname cn)
{
return "welcome to filtering : "+cn.Empid+""+cn.Empname;
}
This is how you will be able to send multiple parameters through actionLink.
For this situation please refer to the code below:
#Html.ActionLink("Link text", "Action Name", null, routeValues: new { pram_serviceLine = Model.ServiceLine_ID, pram_Month = Model.Month, pram_Year = Model.Year, flag = "ROTATION" }
Reply if it works.

Resources