action calling repeatedly using partialviews through list - c#

I have list of resumes on which jobseeker can add note and send message to each of them. So I created partial view of resume. I used Ajax.Beginform method in partial views. On partial view there is submit option. Now when I call a specific resume partial view it calls the action and perform the job but not single time it repeats for each resume item. So why is the action called repeatedly? My View is here
#model NoteViewModel
<script src="~/Content/scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div class="app-tab-content" id="two-1">
#using (Ajax.BeginForm("AddNote","Employer",new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result" }))
{
if(#Model!=null)
{
<input type="text" name="note" />
<input type="hidden" value="#Model.Res_id" name="res" />
<input type="hidden" value="#Model.Job_id" name="job" />
#*<button type="submit" value="AddNote"></button>*#
<input type="submit" id="AddNote" value="Add Note" />
}
}
<div id="result">
#if(ViewBag.NoteMessage!=null)
{
<p>ViewBag.NoteMessage</p>
}
</div>
</div>
Here is an action method
public ActionResult AddNote(string note, int? res, int? job)
{
jpc_resume_job jr = db.jpc_resume_job.Where(m => m.job_id == job && m.resume_id == res).FirstOrDefault();
if (ModelState.IsValid)
{
jr.note = note;
db.Entry(jr).State = EntityState.Modified;
db.SaveChanges();
ViewBag.NoteMessage = "Note Added Successfully";
return PartialView("Addnote");
}
ViewBag.NoteMessage = "Note Not Added Successfully";
return PartialView("Addnote");
}
I am calling this in searchresume view like this:
Foreach(var item in resume)
{
#Html.Partial("Addnote");
}
An image is attached for what exactly I want

Related

Passing data from partial view to parent view

I am trying to pass a value from partial view to parent view. I tried the below which didn't worked for me. Can some one help me out how can I achieve this? By using the value that partial view returned, I am trying to hide a button which is in the parent view.
Parent View:
<div id="ProductCount">
#{
Html.RenderAction("ProductPartialView", "ProductList", new { area = "PR", ProductID = Model.ProductID, allowSelect = true});
}
<div class="saveBtnArea">
<input type="submit" value="Submit App" id="btn-submit" />
</div>
jQuery(document).ready(function () {
var ProductCount = jQuery("#ProductCount").val();
if (ProductCount == 0) {
jQuery("#btn-submit").hide();
}
else {
jQuery("#btn-submit").show();
}
});
Partial View:
<fieldset>
<div>
<input type="hidden" id="ProductCount" value="5" />
</div>
</fieldset>
You can implement change event for hidden input field like this
$('#ProductCount').change(function(){
var ProductCount = $(this).val();
if (ProductCount == 0) {
jQuery("#btn-submit").hide();
}
else {
jQuery("#btn-submit").show();
}
}).trigger('change');
$('#ProductCount').val(5);
$('#ProductCount').change(function(){
var ProductCount = $(this).val();
if (ProductCount == 0) {
jQuery("#btn-submit").hide();
}
else {
jQuery("#btn-submit").show();
}
}).trigger('change');
$('#ProductCount').val(5);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='hidden' id='ProductCount' />
<button id='btn-submit'>Submit</button>

Different buttons in view to perform different operation in mvc

I am facing some problem in MVC
Inside view I have 2 buttons, one is for final submit and the other is for adding dynamic content to the view. Again both are used to post the form. I wanted to know how these would be used in controller.
example
If I click final submit, it will redirect to some view or any other operation and also if I click add button in the same view I want to return to the same view.
note: I am using both buttons to post the same action.
<input type="submit" name="actionBtn" value="add value" />
<input type="submit" name="actionBtn" value="finalsubmit" />
in Action
public ActionResult YourPostAction(string actionBtn)
{
if(actionBtn == "Add Value")
{
}
else if(actionBtn == "finalSubmit")
{
}
}
Another way if you want ( You have to play with name but different way)
#using (Html.BeginForm())
{
<input type="hidden" name="actionName" id="hdnAction" />
<input type="submit" value="test" name="actionBtn" onclick="setThis('test')" />
<input type="submit" value="test1" name="actionBtn" onclick="setThis('test1')"/>
}
<script language="javascript">
function setThis(obj) {
document.getElementById('hdnAction').value = obj;
}
</script>
In controller action
[HttpPost]
public ActionResult Index(string actionName)
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}

Text response displayed in a view's unbound label

I have a view that contains a submit button. When that submit button is clicked some code runs a process. I want to return a text message to a label on the view that will let the user know that their submission was successful or there was an error.
I've searched around and I have found many examples about labels but I haven't come across one that shows me how to do what I want.
My Controller:
public ActionResult Import()
{
//Some code that runs a process
//Need to know what code will return "Import was Successful" or "Erroring Importing"
return RedirectToAction("Import")
}
My View:
#{
ViewBag.Title = "Import";
}
<h2>Import</h2>
#using (Html.BeginForm("Importexcel", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr><td>Import Files</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr>
<tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr>
**<tr><td>#Html.Label(returned results)</td></tr>** // Need to know how to do this
</table>
}
In your view:
#using (Html.BeginForm("Importexcel", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr><td>Import Files</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr>
<tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr>
**<tr><td>#Html.Label(returned results)</td></tr>** // Need to know how to do this
</table>
#ViewBag.Message
}
In your controller:
[HttpPost]
public ActionResult Import(){
//Some code that runs a process
//Need to know what code will return "Import was Successful" or "Erroring Importing"
if(something){
ViewBag.Message = "Import Failed";
}
else
{
ViewBag.Message = "Import Successful";
}
return View();
}
Try and give that a shot.
You can always pass either a key to a look-up table of messages or the message itself via the query string. Here's an example:
Controller Action
public ActionResult Import(string message = null)
{
// Detect presence of message (i.e. !String.IsNullOrWhiteSpace(message)) and show it.
// Additional logic after this...
return RedirectToAction("Import", "YourControllerNameHere", new { message = "Your message here..." });
}
Then it's just a matter of wiring up your model or ViewModel in the Import view so it displays the appropriate message.

How to bind OrderedDictionary?

I try to bind an OrderedDictionary to a view but when the post method gets invoked the Dictionary is always empty.
Here is my code:
[HttpGet]
public ViewResult Edit(string username, string password)
{
Xml test = new Xml(#"c:\Users\pc\Desktop\xml - Copy.xml");
XmlNode userNode = test.GetUserNodeByUsernameAndPassword(username, password);
User user = new User();
user.BindData(userNode);
return View(user.user);
}
[HttpPost]
public ViewResult Edit(OrderedDictionary attributes)
{
return View(attributes);
}
And here is the view:
#using (Html.BeginForm("Edit", "Users")) {
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<p>
<input type="submit" value="Save" />
</p>
#{int counter = 0;}
#{string name = "";}
#foreach (DictionaryEntry attribute in Model)
{
{ name = "[" + counter + "].key"; }
<input type="hidden" name=#name value=#attribute.Key />
#attribute.Key #Html.TextBoxFor(m => attribute.Value)
counter++;
<br />
}
</fieldset>
}
And the result Html looks like this is:
<input type="hidden" value="Username" name="[0].key">
Username
<input id="attribute_Value" type="text" value="Anamana" name="attribute.Value">
So the content of the OrderedDictionary appears fine in the view but when I make a post back the binding isn't working and the directory remains empty.
Concept
To bind a dictionary you have to change the name attribute in the html input tag. Something like this:
In your controller:
[HttpPost]
public ActionResult Edit(IDictionary<string, string> attributes)
{
}
In your HTML:
<input type="text" name="attributes[0].Key" value="A Key" />
<input type="text" name="attributes[0].Value" value="A Value" />
<input type="text" name="attributes[1].Key" value="B Key" />
<input type="text" name="attributes[1].Value" value="B Value" />
The attributes name should be before the index [0] on ther name attribute, because your action expect it.
Tips
I would use the HiddenFor and TextBoxFor HTML Helper of the Asp.Net MVC.
#Html.HiddenFor(model => model[i].Key)
#Html.TextBoxFor(model => model[i].Value)
And it will render in the format that the asp.net mvc will understand and get it working.
For more samples about databind take a look at this link.
Meantime I have found the solution.
I can pass an OrderedDictionary to the view page.
It process it by the following Razor code:
#model System.Collections.Specialized.OrderedDictionary
(...)
#{int counter = 0;}
#{string name = "";}
#foreach (DictionaryEntry attribute in Model)
{
{ name = "[" + counter + "].key"; }
#Html.Hidden(name, attribute.Key)
{name = "[" + counter + "].value";}
#attribute.Key #Html.TextBox(name, attribute.Value)
counter++;
<br />
}
The result HTML's structure fits to the samples which is found in a book, the values from the dictionary appears fine on the page.
After POST was invoked the POST handler function gets the modified values in a Dictionary.
[HttpPost]
public ViewResult Edit(Dictionary<string, string> attributes)
{}
I don't know why but I can't use OrderedDictionary here.

Get html items from view to control

Still kind of new to MVC, so please bear with me. I'm trying to grab some dynamically generated HTML. In this case, list items in my notifyList. I plan on looping through each one in the controller and adding them as database entries. Any help is appreciated, thanks.
View
#model _BaseViewModel
// The form it's within...
#using (Html.BeginForm("Create", "Leaf", FormMethod.Post, new { id = "createForm" }))
<div class="editor-label bottom-area bottom-header">
Notification List:
</div>
<div class="editor-field bottom-area">
<ul id="notifyList"></ul>
</div>
Controller:
[HttpPost]
public ActionResult Create(_BaseViewModel model)
{
// Some loop here
// get html here
db.UserItems.AddObject(model.user);
db.SaveChanges();
//
return RedirectToAction("Index");
}
As far as I understood, you use jQuery to fetch <li/> elements into notifyList. What you need to do here is to generate a hidden input as well. Sample:
$("#btnAppend").click(function() {
for(var i = 0; i < 4; i++) {
var _val = "Foo " + i;
var $li = $("<li/>").text(_val);
var $hidden = #("<input/>").
attr("type", "hidden")
attr("name", "foo").
val(_val);
$hidden.appendTo($li);
$li.appendTo("#notifyList");
}
});
This code will generate following output inside your DOM:
<ul id="notifyList">
<li>Foo 0<input type="hidden" value="Foo 0" name="foo" /></li>
<li>Foo 1<input type="hidden" value="Foo 1" name="foo" /></li>
<li>Foo 2<input type="hidden" value="Foo 2" name="foo" /></li>
<li>Foo 3<input type="hidden" value="Foo 3" name="foo" /></li>
</ul>
When you make a http form post, you can grab the values by the below controller action implementation:
public ActionResult Index(string[] foo) {
foreach(var item in foo) {
//Work with each individual item
}
//continue your code
}
it doesn't work this way. html only exists in the view. the controller has no concept of html (not should it). data sent to the controller comes in 1 of types (GET, POST). there are others, but these are the main to.
get is typically associated with the querystring www.domain.com/mypage.aspx?key=value
where post is the input values from form
<form action="mypage.aspx" method="post">
<input name="key" value="value"/>
<input type="submit" value="click me"/>
</form>
So adding items to a html list won't provide any meaning to the controller. javascript and ajax provide more options on how the data gets sent to the server, but the data is sent, not the markup. and the data is sent as key value pairs.

Categories

Resources