I have a view in my MVC application that is designed to show views and comments gathered from a database, and allow users to make posts and comments accordingly.
The relevant section of Html is below:
<div style="background-color:#fff1fc; height:100vh; width:810px; float:left; border-radius: 8px; margin: 5px">
<div>
<p>
<center>
#foreach (var item in Model.PostList)
{
<div style="background-color: white; height:auto; width: 810px; border-radius: 8px; margin: 5px; text-align: left; text-size-adjust: 50%; text-anchor:start; font-size: larger">
#Html.DisplayFor(modelItem => item.Profile.FirstName)
#Html.DisplayFor(modelItem => item.Profile.LastName)
#Html.DisplayFor(modelItem => item.Project.ProjectName)<br/>
<div style="text-align:center; text-size-adjust: auto">
#Html.DisplayFor(modelItem => item.Text)<br/>
</div>
<div style="text-align: right; text-size-adjust: 20%; text-anchor: end">
#Html.DisplayFor(modelItem => item.DATE)
</div>
<hr />
<div style="line-break:initial; font-size:small; text-align: left; margin: 10px; padding: 10px">
#Html.Label("Comments:")<br/>
<br/>
#foreach (var comment in Model.CommentList)
{
if (comment.PostId == item.Id)
{
#Html.DisplayFor(modelComment => comment.Profile.FirstName)
#Html.DisplayFor(modelComment => comment.Profile.LastName)
<br/>
<center>
#Html.DisplayFor(modelComment => comment.Comment1)
<hr />
<br/>
</center>
}
}
<center>
#Html.TextAreaFor(model => Model.Comment, new { #class = "height: 200px, width: 600px"})
<br />
<br />
<right>
<input type="submit" value="Comment" class="btn btn-default" />
<input type="hidden" name="PostId" value="#item.Id" />
<input type="hidden" name="ProfileId" value="#Model.ProfileList[0].Id" />
</right>
<br />
</center>
</div>
</div>
}
</center>
</p>
</div>
</div>
So, for each item in PostList, the relevant attributes of that list are displayed. With these posts, each item from the CommentList that references this post is also displayed, with a TextBox to make a new comment. This all works fine! The problem appears to be here:
<center>
#Html.TextAreaFor(model => Model.Comment, new { #class = "height: 200px, width: 600px"})
<br />
<br />
<right>
<input type="submit" value="Comment" class="btn btn-default" />
<input type="hidden" name="PostId" value="#item.Id" />
<input type="hidden" name="ProfileId" value="#Model.ProfileList[0].Id" />
</right>
<br />
</center>
For some reason, when I attempt to make a comment on my platform, it only works if commenting on the most recent/first post on the feed (The first item). Attempting to make a comment on anything other than the first item, does nothing. Here is the Post method of my controller:
public ActionResult Post(string Text, int Id, string Comment, int ProfileId, int PostId)
{
if (Text != "")
{
using (var ctx = new SocialDBEntities())
{
string userId = User.Identity.GetUserId();
Post post = new CrowdSocial2.Post();
post.ProfileId = Id;
post.DATE = System.DateTime.Now.Date;
post.Text = Text;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Feed");
}
}
else if (Comment != "")
{
string userId = User.Identity.GetUserId();
Comment comment = new CrowdSocial2.Comment();
comment.PostId = PostId;
comment.ProfileId = ProfileId;
comment.Comment1 = Comment;
comment.Date = System.DateTime.Now.Date;
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Feed");
}
else
{
return RedirectToAction("Feed");
}
}
The controller is passed Comment, and determines whether or not it is "null". If not, it will post the comment to the database with the accompanying postId and profileId. Since this wasn't working, I decided to put a breakpoint on the RedirectToAction both inside of the if(Comment != "") statement, and in the elseif statement to see what was happening.
Turns out, Comment for some reason is being passed as "" regardless of what was written in the comment box, the controller is seeing it as "" and hence just redirects back to the view. This makes me suspect that what is happening is that Comment is being passed from the very first comment box, which is empty.
Any ideas how I can fix this so that I can comment on any of the post items?
Related
I wanted to add search query name to header on my subpage so for example if someone will type John in search box the page that he/she receives is: Searching results for: John
Home Controller:
public ActionResult Search(string searching)
{
IEnumerable<Book> books = from t in Book.allBooks select t;
if (!String.IsNullOrEmpty(searching))
{
books = books.Where(a => a.Title.ToLower().Contains(searching.ToLower()));
}
return View(books.ToList());
}
_Layout.cshtml:
<li class="d-none d-lg-block justify-content-center" style="align-self: center; padding-right: 10px">
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
<i class="fas fa-search" aria-hidden="true" style="padding-right: 5px"> </i>
#Html.TextBox("searching")
<input type="submit" value="Search" />
}
</li>
Search.cshtml:
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#*#Html.TextBox("searching")
<input type="submit" value="Search" />*#
}
#if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Not found any book with this name</h2>
}
else
{
foreach (var item in Model)
{
<div class="col-12 col-md-6 col-lg-6 col-xl-3 align-items-center" style="margin-top: 10px; margin-bottom: 10px;">
<div class="col-md-12 d-flex justify-content-center">
<img src="~/Content/BookImages/#item.Image" class="img-thumbnail" style="height: 400px; width: 250px;" />
</div>
<div class="col-md-12 text-center">
<strong>#Html.ActionLink(item.Title, "Details", "Home", new { id = item.Id }, null)</strong>
</div>
<div class="col-md-12 text-center">
#item.WriterFirstName
</div>
<div class="col-md-12 text-center">
#item.WriterLastName
</div>
</div>
}
}
Thank you for your help
This could work for you:
public ActionResult Search(string searching)
{
IEnumerable<Book> books = from t in Book.allBooks select t;
if (!String.IsNullOrEmpty(searching))
{
books = books.Where(a => a.Title.ToLower().Contains(searching.ToLower()));
}
ViewBag.SearchTerm = searching;
return View(books.ToList());
}
And in your view:
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#*#Html.TextBox("searching")
<input type="submit" value="Search" />*#
}
#if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Not found any book with this name</h2>
}
else
{
<h2 style="margin-top: 30px">Search results for: #ViewBag.SearchTerm</h2>
foreach (var item in Model)
{
<div class="col-12 col-md-6 col-lg-6 col-xl-3 align-items-center" style="margin-top: 10px; margin-bottom: 10px;">
<div class="col-md-12 d-flex justify-content-center">
<img src="~/Content/BookImages/#item.Image" class="img-thumbnail" style="height: 400px; width: 250px;" />
</div>
<div class="col-md-12 text-center">
<strong>#Html.ActionLink(item.Title, "Details", "Home", new { id = item.Id }, null)</strong>
</div>
<div class="col-md-12 text-center">
#item.WriterFirstName
</div>
<div class="col-md-12 text-center">
#item.WriterLastName
</div>
</div>
}
}
Mind you, this is a quick and dirty solution. The proper one would be to create a ViewModel and add both books and the search term.
public class SearchBookViewModel {
public IEnumerable<Book> Books {get; set;}
public string SearchTerm {get; set;}
}
If you can't change the ViewModel then go with the ViewBag. The bad thing about the ViewBag, is that if someone changes the code in the controller, then you will only find out during runtime.
I have a form which has a DropDownList to select users and a form for user data. All controls are nested inside a form.
Cureently user DropDownList submits the form to notify about user selection to fetch appropriate data.
I want have a Button type(submit) which saves the data for the current user. Since both controls are in the same form and they both do submit, how can I differentiate if I am trying to select the user or saving the data in my action?
I have tried creating two forms as follows:
#model MyApp.Models.UserModel
#{
ViewBag.Title = "Profiles";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" src="chosen.jquery.js"></script>
<script type="text/javascript" src="bootstrap-switch.js"></script>
<link rel="stylesheet" href="chosen.css" />
<link rel="stylesheet" href="bootstrap-switch.css" />
<style type="text/css">
.chosen-search{
display: none;
}
.form-group label{
margin-top: 10px;
}
.row{
margin-bottom: 20px;
}
th{
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#CurrentUserId').chosen({placeholder_text_single: "Select a user"});
$('#CurrentGroupId').chosen({placeholder_text_single: "Select a group"});
$('#CurrentRoleId').chosen({placeholder_text_single: "Select a role"});
$('#IsActive').bootstrapSwitch({
onColor: "success",
offColor: "danger",
onText: "ACTIVE",
offText: "PASSIVE",
animate: false,
handleWidth: 60
});
$('.authorizationCheckBox').bootstrapSwitch({
onColor: "success",
offColor: "danger",
onText: "Y",
offText: "N",
animate: false,
size: "mini"
});
});
</script>
#using (Html.BeginForm("Profile", "User"))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-3">
<div class="row">
<label class="control-label">Selected user :</label>
</div>
</div>
<div class="col-sm-9">
<div class="row">
#Html.DropDownListFor(x => x.CurrentUserId, new SelectList(Model.AllUsers, "Id", "Username"), "", new { #class = "form-control", onchange = #"this.form.submit();" })
</div>
</div>
</div>
}
#using (Html.BeginForm("SaveProfile", "User"))
{
if (!string.IsNullOrWhiteSpace(Model.CurrentUser))
{
<div class="row">
<div class="col-sm-3">
<div class="row">
#if (string.IsNullOrWhiteSpace(Model.UserImageUrl))
{
<img src="no-user.png" class="img-circle" alt="..." style="width: 35%; display: block; margin: auto;">
<button type="button" class="btn btn-primary" style="display: block; margin: auto; margin-top: 10px;">
<span class="glyphicon glyphicon-upload"></span> Upload avatar
</button>
}
else
{
<img src="#Model.UserImageUrl" class="img-circle" alt="..." style="width: 35%; display: block; margin: auto;">
<button type="button" class="btn btn-primary" style="display: block; margin: auto; margin-top: 10px;">
<span class="glyphicon glyphicon-retweet"></span> Change avatar
</button>
}
</div>
<div class="row">
<div class="input-group" style="margin: 0 auto;">
<div class="switch-button xlg showcase-switch-button">
#Html.CheckBoxFor(x => x.IsActive)
</div>
</div>
</div>
</div>
<div class="col-sm-9">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Username :</label>
<div class="col-sm-10">
<input id="CurrentUser" name="CurrentUser" class="form-control form-control-flat" value="#Model.CurrentUser" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">E-mail :</label>
<div class="col-sm-10">
<input id="EMail" name="EMail" class="form-control form-control-flat" value="#Model.EMail" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Membership :</label>
<div class="col-sm-10">
#Html.DropDownListFor(x => x.CurrentGroupId, new SelectList(Model.AllGroups, "Id", "Name"), "", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Role :</label>
<div class="col-sm-10">
#Html.DropDownListFor(x => x.CurrentRoleId, new SelectList(Model.AllRoles, "Id", "Name"), "", new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<button id="btnSave" type="submit" class="btn btn-info" style="float: right; margin-right: 10px; margin-bottom: 40px;">
<span class="glyphicon glyphicon-trash"></span>Save changes
</button>
}
}
[HttpGet]
public ActionResult Profile()
{
return View(CreateInitialUserModel());
}
[HttpPost]
public ActionResult Profile(UserModel model)
{
model = GetUserModel(model.CurrentUserId.Value);
ModelState.Clear();
return View(model);
}
[HttpPost]
public ActionResult SaveProfile(UserModel model)
{
SaveModel(model)
return RedirectToAction("Profile");
}
But the problem is, at HttpPost of Profile action works well. But when I click the Save button and the HttpPost SaveProfile action is called, input parameter model does not have the values set on the screen.
I would actually use two forms. Not only does it relieve your problem here, as you can just add a hidden field or something to each form to indicate which was submitted, but it prevents other issues you're likely to run into, like failing validation on any required user fields in the create form, when you just select a user, because no data was submitted for those fields.
Short of that, just use whatever JavaScript you're already using to automatically submit when an option is selected from the drop down to change a value of a hidden field or otherwise modify the post data before it's submitted.
Why not use jquery for data retrieval? You could switch you dropdown to instead call a jquery function that performs an ajax call to a controller method that retrieves the relevant user data. Then, you can bind the data to the appropriate fields on the page using jquery. You would then only have one submit button on your view, handled through the normal mvc form process.
-in drop downdown list change event ,you should store UserID to a variable like global variable or hiddenfields.
-Create a Button
in function=
function submitvalues()
{
//get stored userID here from variable
//perform submit here
}
I'm using razor html and attempting to post data to a function. I can get parts of the data to submit and go across just fine but other parts i can not.
#using (Html.BeginForm("Reply", "api/Reply", new { ID = Model.ID, UserName = Model.Username }))
{
<div id="mainArea" class="lightboxContent" style="display: block">
<div class="lightboxText">
<div class="responderTitleLeft">Select Profile: </div>
<div class="responderFormFloat">
<select name="profileSelector" class="select-style">
<option value="Select One" selected>Please Select Your Profile</option>
#foreach (var profile in Model.ProfileModels)
{
<option value="#profile.ProfileID">#profile.ScreenName</option>
}
</select>
</div>
<div class="responderActions">
<div id="Reply" class="TwtiterReply">
<a href="javascript:void(0)">
<img src="/images/engage/actions/reply.png" onclick="toggle('ReplyArea')" title="Reply to message" />
</a>
</div>
<div id="ReplyArea" style="display: none;" class="responderForm">
<div class="responderTitle">Reply</div>
<textarea id="MessageEdit" name="Message" onkeyup="return characterCount(this)" onchange="postChange(this.id, 'messagePreview');" rows="4" cols="50" style="resize: none">#Model.Username</textarea>
<p id="counter"><strong><span id="charCount">140</span></strong> more characters available.</p>
<div class="lightboxButtonsBar">
<input type="button" onclick="toggle('mainArea')" tabindex="3" value="Reply" />
<input type="button" class="cancel" tabindex="4" value="Cancel" />
</div>
</div>
</div>
</div>
</div>
<div id="confirmArea" class="confirmationArea" style="display: none">
<div class="warning">
<p><strong>Warning:</strong></p>
</div>
<div class="warningMessage">
<p>You are posting from #Model.ProfileModels with the message:</p>
<div class="messagePreviewArea" data-form="Reply">
<p>
<textarea id="messagePreview" readonly rows="4" cols="50" style="color: #ffffff; font-size: .9em; background-color: transparent; resize: none; border-color: #808080;"></textarea></p>
<input type="submit" tabindex="3" value="Confirm" />
<input type="button" onclick="toggle('mainArea')" tabindex="3" value="Cancel" />
</div>
</div>
</div>
}
public UserProfile Reply(string ID, string UserName, FormCollection form)
{
var pSelector = form["profileSelector"];
var message = form["Message"];
ApiService msgserv = new ApiService();
UserProfile up = UserProfile.GetFirst(new Guid(pSelector));
messenger.Reply(up.key, UserName, ID, message);
return up;
}
what i'm looking to get out of this form (in order of how it's show) ID, and username (they are provided by the model and i get those no problem.)
The ones i'm having issues with is the profile selector and the text area with the name message.
Can someone point me in the right direction on how to get a textarea and a select into a form?
The reason the select is not providing the model with data is because its name property is not set to corresponing property name in the model. The same goes for the text area. Generally speaking, if you want the form submit to fill those property you use the 'strongly-typed' helper methods, such as DropdownFor and CheckBoxFor. Or you can manually wire those up, try setting the name of the select element to "SelectedProfile" and changing the Reply action to: Reply(string ID,string Username,string SelectedProfile, FormCollection form)
To get from the textarea do something like this on your view #Html.TextArea("messagePreview"); But I would recommend saving things in your model if you can.
I have a contact page in mvc . I have a 4 text box in this page and
one text area and i want to give validation using jquery the
text-box id is txtbxName, txtbxCompany, txtbxEmail, txtbxPhone ,and
txtarMessage. when user click on submit button if txtbxName is blank.
i want a message something like this "Please enter your Name!" and so
on. please help me thanks
ContactController.cs
public ViewResult Create(string Name, string Company, string Regarding, string Email, string Phone, string Message)
{
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
try
{ MailMessage mail = new MailMessage(); mail.From = new MailAddress("g#technosys.com");
mail.To.Add("p#technosys.com");
mail.Subject = "Accept Request";
mail.Body = body;
mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Credentials = new System.Net.NetworkCredential("g#technosys.com", "1457898");
smtp.EnableSsl = true;
// smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
catch (Exception ex)
{
ViewData.ModelState.AddModelError("_FORM", ex.ToString());
}
return View();
Jquery
$("#btnSubmit").click(function (event) {
var data = { Name: $("#txtbxName").val(), Company: $("#txtbxCompany").val(), Regarding:
$("#ddlRegarding").val(), Email: $("#txtbxEmail").val(), Phone: $("#txtbxPhone").val(), Message:
$("#txtarMessage").val()
}
$.ajax({
type: "POST",
url: "/Contact/Create", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "html",
success: function (result) {
$("#txtbxName").val("");
$("#txtbxCompany").val("");
$("#txtbxEmail").val("");
$("#txtbxPhone").val("");
$("#txtarMessage").val("");
alert(result);
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
$("#txtbxName").val("");
$("#txtbxCompany").val("");
$("#txtbxEmail").val("");
$("#txtbxPhone").val("");
$("#txtarMessage").val("");
alert('Thanks for sending info');
return false;
}
});
});
Index .cshtml
<div class="parteners">
<div class="block" style="width: 270px;">
<div class="block" style="width: 295px; padding: 3px;">
Name :
</div>
<div class="block" style="width: 320px; padding: 3px;">
<input type="text" class="textbox" name="textfield" alt="Type our Name here" />> <br />
</div>
<div class="block" style="width: 295px; padding: 3px;">
Company :
</div>
<div class="block" style="width: 295px; padding: 3px;">
<input type="text" class="textbox" name="textfield2" />
</div>
<div class="block" style="width: 295px; padding: 3px;">
Regarding :
</div>
<div class="block" style="width: 295px; padding: 3px;">
<select name="select" class="textbox">
<option>General Inquiry</option>
<option>Programming Related Question</option>
<option>Website Quote Request</option>
<option>Feedback</option>
<option>Help and Support</option>
</select>
</div>
</div>
<div class="block" style="width: 270px;">
<div class="block" style="width: 295px; padding: 3px;">
Email :</div>
<div class="block" style="width: 295px; padding: 3px;">
<input type="text" class="textbox" name="textfield3" />
</div>
<div class="block" style="width: 295px; padding: 3px;">
Phone :
</div>
<div class="block" style="width: 295px; padding: 3px;">
<input type="text" class="textbox" name="textfield4" />
</div>
</div>
<div class="block" style="width: 600px; padding: 3px;">
Enter your Suggestions / Comments / Feedback here :
</div>
<br />
<div class="block" style="width: 600px; padding: 3px;">
<textarea class="textarea" name="textarea"></textarea><br />
<br />
</div>
<div class="block" style="width: 600px; padding: 3px;">
<input id="Button1" type="Button" value="Submit" />
</div>
</div>
Set class to all the textboxes like below
<input type="text" class="valcheck" title="Name" id="your_name_field_id" name="your_name_field_name" />
do the same for all the 6 textboxes.
$("#btnSubmit").click(function (event) {
$(".valcheck").each(function(){
var id = this.id;
var field_value = $("#"+id).val();
if(field_value=="")
{
var field_name = $("#"+id).attr('title');
$("#error_display_div").append("Please enter "+field_name+"<br />");
}
//Show hide error_display_div accordingly, you can clear out the div using
// $("#error_display_div").html('');
});
});
You should look into the jQuery validation plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
You should consider using a ViewModel like this:
public class MessageVM
{
public string CompanyName {get;set;}
[Required]
public string Name {get;set;}
public string Regarding {get;set;}
public string Message {get;set;}
[Required]
public string Email {get;set;}
}
Which uses DataAnnotations. You use this in your view to bind to like so:
#Model Your.Namespace.ViewModels.MessageVM
#using(Html.BeingForm("create"))
{
#Html.LabelFor(x => x.Name)
#Html.TextBoxFor(x => x.Name)
#Html.LabelFor(x => x.CompanyName)
#Html.TextBoxFor(x => x.CompanyName)
#Html.LabelFor(x => x.Regarding)
#Html.TextBoxFor(x => x.Regarding)
#Html.LabelFor(x => x.Email)
#Html.TextBoxFor(x => x.Email)
#Html.LabelFor(x => x.Message)
#Html.TextBoxFor(x => x.Message)
<button type="submit">Send!</button>
}
And then you can set up a method on your controller something like the below
public ActionResult Create(MessageVM message)
{
if (!ModelState.IsValid)
{
return View(message);
}
//else do whatever you need, send the email etc.
}
Bit more here
I have this script that basically has 4 select boxes, what I want is that for the 2 top select boxes, he submits the optionvalue that is selected to an action (which can be found at "ProductKoppeling/ProductKoppelingPartial"), I want to let him submit this data when I click on an option but without page refresh.
I tried JSON and I tried Ajax, but I didn't get it working..
How should i do this?
Script:
<script language="javascript" type="text/javascript">
function delete_1() {
var answer = confirm("U staat op het punt dit product te verwijderen, wilt u doorgaan?")
if (answer) {
document.getElementById('Actie_1').value = '5';
document.getElementById('hpg_submit').submit();
}
}
function delete_2() {
var answer = confirm("U staat op het punt dit product te verwijderen, wilt u doorgaan?")
if (answer) {
document.getElementById('Actie_2').value = '6';
document.getElementById('pg_submit').submit();
}
}
function delete_3() {
var answer = confirm("U staat op het punt dit product te verwijderen, wilt u doorgaan?")
if (answer) {
document.getElementById('Actie_3').value = '6';
document.getElementById('p_submit').submit();
}
}
</script>
CSHTML:
<div style="width: 500px; float: left;">
#using (Html.BeginForm("ProductKoppelingPartial", "ProductKoppeling", FormMethod.Post, new { id = "onload_submit" }))
{
#Html.DropDownList("Klant.Id", (ViewBag.Klant as SelectList), new { onchange = "document.getElementById('onload_submit').submit()" })
}
<div style="clear: both"></div>
<div style="float: left;">
<b>Hoofdgroepen</b><br />
#using (Html.BeginForm("ProductKoppelingPartial", "ProductKoppeling", FormMethod.Post, new { id = "hpg_submit" }))
{
if (ViewBag.SelectedKlant != null)
{
<input type="hidden" name="Klant.Id" value="#ViewBag.SelectedKlant.Id" />
}
<select style="width: 200px;" size="6" id="HoofdProductGroep" name="HoofdProductGroep.Id" onchange="document.getElementById('hpg_submit').submit();">
#foreach (var hpg in ViewBag.HoofdProductGroep)
{
if (ViewBag.SelectedHPG != null)
{
if (hpg.Id == ViewBag.SelectedHPG.Id)
{
<option value="#hpg.Id" selected="selected">#hpg.Naam</option>
}
else
{
<option value="#hpg.Id">#hpg.Naam</option>
}
}
else
{
<option value="#hpg.Id">#hpg.Naam</option>
}
}
</select>
<input type="hidden" name="Actie" id="Actie_1" value="0" />
<br />
<img src="../../Content/toevoegen.png" style="cursor: pointer; width: 30px;" onclick="document.getElementById('Actie_1').value='1';document.getElementById('hpg_submit').submit();" />
<img src="../../Content/bewerken.png" style="cursor: pointer; float: none; width: 30px;" onclick="document.getElementById('Actie_1').value='2';document.getElementById('hpg_submit').submit();" />
<img src="../../Content/verwijderen.png" style="cursor: pointer; float: none; width: 30px;" onclick="delete_1()" />
}
</div>
<div style="float: right;">
<b>Groepen</b><br />
#using (Html.BeginForm("ProductKoppelingPartial", "ProductKoppeling", FormMethod.Post, new { id = "pg_submit" }))
{
if (ViewBag.SelectedHPG != null)
{
<input type="hidden" name="HoofdProductGroep.Id" value="#ViewBag.SelectedHPG.Id" />
}
if (ViewBag.SelectedKlant != null)
{
<input type="hidden" name="Klant.Id" value="#ViewBag.SelectedKlant.Id" />
}
<select size="6" style="width: 200px;" id="ProductGroep_Id" name="ProductGroep.Id" onchange="document.getElementById('pg_submit').submit();">
#foreach (var pg in ViewBag.ProductGroep)
{
if (ViewBag.SelectedPG != null)
{
if (pg.Id == ViewBag.SelectedPG.Id)
{
<option value="#pg.Id" selected="selected">#pg.Naam</option>
}
else
{
<option value="#pg.Id">#pg.Naam</option>
}
}
else
{
<option value="#pg.Id">#pg.Naam</option>
}
}
</select>
<input type="hidden" name="Actie" id="Actie_2" value="0" />
<br />
<img src="../../Content/toevoegen.png" style="cursor: pointer; width: 30px;" onclick="document.getElementById('Actie_2').value='3';document.getElementById('pg_submit').submit();" />
<img src="../../Content/bewerken.png" style="cursor: pointer; float: none; width: 30px;" onclick="document.getElementById('Actie_2').value='4';document.getElementById('pg_submit').submit();" />
<img src="../../Content/verwijderen.png" style="cursor: pointer; float: none; width: 30px;" onclick="delete_2()" />
}
</div>
<div style="clear: both; height: 25px;"></div>
#using (Html.BeginForm("Save", "ProductKoppeling", FormMethod.Post, new { id = "p_submit" }))
{
<div style="float: left">
<b>Producten</b><br />
<select size="18" style="width: 200px;" name="Product.Id">
#foreach (var p in ViewBag.Product)
{
<option value="#p.Id">#p.Naam</option>
}
</select>
#if (ViewBag.SelectedPG != null)
{
if (ViewBag.SelectedPG.Id != null)
{
<input type="hidden" name="ProductGroep.Id" value="#ViewBag.SelectedPG.Id" />
}
}
<input type="hidden" name="Actie" id="Actie_3" value="0" />
<br />
<img src="../../Content/toevoegen.png" style="cursor: pointer; width: 30px;" onclick="document.getElementById('Actie_3').value='1';document.getElementById('p_submit').submit();" />
<img src="../../Content/bewerken.png" style="cursor: pointer; float: none; width: 30px;" onclick="document.getElementById('Actie_3').value='2';document.getElementById('p_submit').submit();" />
<img src="../../Content/verwijderen.png" style="cursor: pointer; float: none; width: 30px;" onclick="delete_3()" />
<br />
</div>
<div style="float: left; width: 100px;">
<center>
<br /><br /><br /><br />
<a style="cursor: pointer; float: none; color: blue; font-size: 30px;" onclick="document.getElementById('p_submit').submit();">»</a>
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<a style="cursor: pointer; float: none; color: blue; font-size: 30px;" onclick="document.getElementById('pgp_submit').submit();">«</a>
</center>
</div>
}
<div style="float: right;">
<b>Producten in groepen</b><br />
#using (Html.BeginForm("Delete", "ProductKoppeling", FormMethod.Post, new { id = "pgp_submit" }))
{
<select size="18" style="width: 200px;" name="ProductGroepProduct.Id">
#foreach (var pgp in ViewBag.ProductGroepProduct)
{
if (pgp != null)
{
if (pgp.Product != null)
{
<option value="#pgp.Id">#pgp.Product.Naam</option>
}
}
}
</select>
}
</div>
You are using a Html Form.
This causes a refresh by default.
Use an ajax form or don't use forms at all and just call an action but don't return an action result.
Create a controller similar to:
public void Action(String paramater)
{
...
}
When you call it from the view it will execute the code on the server side without causing any effects on the client.
As Requested:
Added Non refresh Ajax form example:
$.ajax({
type: "POST",
url: "URL",
data: dataString,
success: function() {
...
};
});
return false;
The return false prevents a refresh.
Follow this guide for a full tutorial.
Maybe you should use Ajax calls ... and choose the div you wish to refresh : here is a short example :
AjaxOptions ajaxOptions = new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "Mydiv",
OnSuccess = "aJqueryFunction"
};
And in your ajax call :
<div id="Mydiv">
#using (Ajax.BeginForm("text", "Action",(optional)"Cotroller", ajaxOptions))
{}
</div>